RE: [PHP-DB] generating unique id's

From: Date: Wed, 28 Jun 2000 22:26:51 +0000
Subject: RE: [PHP-DB] generating unique id's
References: 1  Groups: php.db 
Request: Send a blank email to php-db+get-718@lists.php.net to get a copy of this message
<snip> I need to generate a unique id. The problem I am running into is this: I have a for loop that generates a bunch of id's using the time() function, the problem is that since the for loop only takes less than a microsecond, and the precision of the time() function is a microsecond, all the id's are the same. I looked into using uniqid(), which according to the PHP manual generates an INT. However, I tested it out, and in a microsecond it DOES generate a series of different, random STRINGS, mix of ints and characters, NOT an INT, which like I said is what the PHP manual uses. MySQL requires that the primary key be an INT, so I can use uniqid() function to generate this id, because its a string. </snip> Actually I believe MySQL requires the primary key to be an INT, unique and the column must be auto-incrementing meaning that you can't really assign unique IDs for it (MySQL does it automatically). My question would be why would you want to create your own unique IDs instead of letting MySQL do it for you? You didn't provide any of your code so I'm assuming the mistake you're making is the fact you're reseeding the rand (or mt_rand) function at the beginning or end of the loop ie <? for ($i = 0; $i < 1000; $i++) { mt_srand((double)microtime()*1000000); $randval = mt_rand(); } ?> This *could* cause duplicates because as you say if you're in the same microsecond you'll get the same values...HOWEVER if you seed the randomizer once and then use the random function in the loop I think you'll be happy. <? mt_srand((double)microtime()*1000000); for ($i = 0; $i < 1000; $i++) { $randval = mt_rand(); } ?> The downside to this is that it still doesn't not guarantee uniqueness...there's always the possibility of the rand function duplicating one or more numbers in the course of the loop... Sincerely, Craig Vincent

« previous php.db (#718) next »