How do I create a random unique string in MySQL?
when I need to create a random string in PHP I use this function:
public function generateString($length)
{
$charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for($i=0; $i<$length; $i++)
$key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
return $key;
}
Then I would take the generated string and store it in a MySQL database.
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?
Maybe something like this?
while(++$i < 100)
{
//query db with random key to see if there is a match
//if no match found break out of loop
break;
}
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?