title: PHP/MySQL - Best way to create unique random string?
body: <p>How do I create a random unique string in MySQL?</p>
  
  <p>when I need to create a random string in PHP I use this function:</p>
  
  <pre><code>public function generateString($length)
  {   
      $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  
      for($i=0; $i&lt;$length; $i++) 
          $key .= $charset[(mt_rand(0,(strlen($charset)-1)))]; 
  
      return $key;
  }
  </code></pre>
  
  <p>Then I would take the generated string and store it in a MySQL database. </p>
  
  <p>What is the best way to make sure the generated random string is unique to all the other random strings created for other entries in the database? </p>
  
  <p>Maybe something like this?</p>
  
  <pre><code>while(++$i &lt; 100)
  {
    //query db with random key to see if there is a match
  
    //if no match found break out of loop
    break;
  
  }
  </code></pre>
  
  <p>This seems messy and long, and I could potentially hit the database multiple times.  How can I quickly be sure my new random string is unique?</p>