RE: [PHP-DB] generating unique id's
| From: | Chris Hughes | Date: | Wed, 28 Jun 2000 22:29:12 +0000 |
| Subject: | RE: [PHP-DB] generating unique id's | ||
| References: | 1 | Groups: | php.db |
| Request: | Send a blank email to php-db+get-719@lists.php.net to get a copy of this message | ||
The problem I've had with letting mysql generate its own ids is there seems
to be a problem with how records are removed. For example, one problem I
had was when we had high traffic hitting the db and records where being
removed and added at a frantic pace, mysql choked a couple of times on
inserting a no-unique id. May be something I did with DB setup or lock
type, but non the less, I like to generate my own unique id's
-----Original Message-----
From: Craig Vincent [mailto:2bunnyhop@home.com]
Sent: Wednesday, June 28, 2000 4:27 PM
To: Cody Caughlan
Cc: php-db@lists.php.net
Subject: RE: [PHP-DB] generating unique id's
<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
--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, e-mail: php-db-unsubscribe@lists.php.net
For additional commands, e-mail: php-db-help@lists.php.net
To contact the list administrators, e-mail: php-list-admin@lists.php.net