John John - 3 months ago 84x
SQL Question

PHP/MySQL - Best way to create unique random string?

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


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?


Assuming 10 characters from the character set a-z, A-Z, 0-9 mean there are (26 + 26 + 10)10 = 8.39299366 × 1017 possible combinations. To calculate the odds of a collision... just 1/x the afore-mentioned number. So I would not be worrying about getting the same string twice. Even if do get the same string again I'll just run the function again in a loop, the only exit condition being that a unique string is found.