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($le
I would make the column of this id unique in your DB. Then you can do something like this to safeguard against collisions:
$row_count = 0;
while ($row_count == 0) {
error_reporting(0);
$id_string = substr(uniqid(), 0, 10);
$sql = "UPDATE <table> SET unique_id = :unique_id WHERE <something true>";
$query = $this->db->prepare($sql);
$query->execute(array(':unique_id' => $unique_id));
$row_count = $query->rowCount();
}
Sure, it may need to try the query more than once, but this way you know it's guaranteed to be unique in your DB. The error_reporting(0) line is in there to suppress any warnings which might be turned on. PHP's uniqid() also isn't the most unique generate there is, but you can easily swap that out for your own or just take the hit of potential collisions here and there.
Take a look at the uniqid function and the pecl uuid extension. Either one can be used as the basis for generating guids, although if you plan to have a cluster, you will want to insure that you have something extra that insures that two servers don't generate the same id. Having a per server configuration that adds as prefix or suffix to the id is sufficient to address that issue.
If you want to use these strings for security purpose, you should use openssl_random_pseudo_bytes which will indicate you if PHP was able to use a strong algorithm to generate it:
Ouput needs some cleaning though. Have a look at this question for more info.
SET rand_str = SUBSTRING(MD5(NOW()),1,$LENGTH);
-- Where LENGTH is 1 to 32 as per MD5
Some examples are below:
SET rand_str = SUBSTRING(MD5(NOW()),1,5);
-- 5 character string
SET rand_str = SUBSTRING(MD5(NOW()),1,15);
-- 15 character string
Why not just use the built-in functions for generating unique identifiers? You wouldn't have to worry about duplicates that way.
Both PHP and MySQL have their own.
PHP: uniqid()
MySQL: UUID()
Luckily databases already have the ability to create unique IDs (numeric) - I suggest the approach that we took, which is to create a two-way conversion between a gently increasing numeric ID and an alpha-numeric ID. Having it be two-way assures that the alpha-numeric "random" versions are also unique without having to explicitly test them. Indeed, I only ever store the numeric version in the database (since you get it for free with a SERIAL column) and only ever print the alpha version.
This example generates seven-byte IDs but the approach can be trivially tweaked to fit almost any set of circumstances.
See: How to generate unique id in MySQL?