Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

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?

like image 884
John Avatar asked Oct 25 '11 17:10

John


1 Answers

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()

like image 78
Mark Biek Avatar answered Oct 04 '22 01:10

Mark Biek