Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would use this function, very simple:</p> <pre><code>/** * Generates a string with random characters taken from the given string * of the desided length * * @param int $length the resulting string length * @param string $chars the chars; defaults to all alphanumerics * @return string the random string * @author Andrea Baron */ function rand_string($length, $chars = 'qwertyuiopasdfghjklzxcvbnm0123456789') { $r = ''; $cm = strlen($chars)-1; for($i=1; $i&lt;=$length; ++$i) { $r .= $chars[mt_rand(0, $cm)]; } return $r; } </code></pre> <p>then you can do something like this</p> <pre><code>$used = $db-&gt;prepare('SELECT EXISTS(SELECT string FROM table WHERE string = ?)'); do { $string = rand_string(32); $used-&gt;execute(array($string)); $exists = $used-&gt;fetch(PDO::FETCH_NUM); $used-&gt;closeCursor(); } while($exists &amp;&amp; $exists[0]); $ins = PP::$db-&gt;prepare('INSERT INTO table SET string=?'); $ins-&gt;execute(array($string)); </code></pre> <p>if you use PDO and MySQL; I would set the string field as Primary Key, or a HASH index if on a secondary field; or more concise and, maybe, not as strong:</p> <pre><code>do { $string = rand_string(32); $exists = PP::$db-&gt;exec('INSERT INTO a SET string='.PP::$db-&gt;quote($string)); } while(!$exists); </code></pre> <p>this because <code>exec()</code> returns the number of affected rows on no error, or false if there's an error, in this case a duplicate key value.</p> <p>Or, as an alternative, you can add a timestamp and forget about checking at all. Like:</p> <pre><code>$string = rand_string(8).time(); </code></pre> <p>The probability of having a duplicate identifier resets each second, and, with 8 characters, as you see is 1 in 37^8, or 3.5E12.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload