views:

293

answers:

3

hello. i'm building an application that needs a random unique id for each user not a sequence

mysql database

ID   Username

for my unique random ID, what is the best way to do that?

+1  A: 

PHP provides a uniqid function, which might do the trick, I suppose.

Note it's returning a string, though, and not an integer.


Another idea would be to generate / use some GUID -- there are some proposals about that in the user notes of the manual page of uniqid.

Pascal MARTIN
if i use something like $unique_id = unique(); should i check if this id is already exists in the database? or not ?
From.ME.to.YOU
There is always a risk (very small, but existant) that a same "unique" id is generated twice... So you have to deal with that possibility ;;; still, as it's highly unlikely, I would use an UNIQUE index in the Database, try to insert, and only deal with the "insert failed because of duplicate entry" problem -- i.e. I would not check before inserting *(but that's not the cleanest way ^^ )*
Pascal MARTIN
+1  A: 

I would still have the normal auto-increment primary key to identify each row properly, it's just standard convention.

I'd then have another indexed column called 'user_id' or something and use uniqid(); for it.

Stephen Melrose
if i use something like $unique_id = unique(); should i check if this id is already exists in the database? or not ?
From.ME.to.YOU
You should if you're not sure the `$unique_id` is truly unique.
Douwe Maan
+1  A: 

MySQL provides a function called UUID():

http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_uuid

Documentation claims this:

A UUID is designed as a number that is globally unique in space and time. Two calls to UUID() are expected to generate two different values, even if these calls are performed on two separate computers that are not connected to each other.

This should cover your needs.

Álvaro G. Vicario
to me the words "are expected" is not quite the same as "will" or "guaranteed". you have to remember that the correct term is "pseudo random numbers" which are not the same as random numbers, i.e. truly random, and potentially will not be random, can repeat after a number of iterations, will produce the same number sequence from the same seed etc. (Read Donald Knuth's chapter on this in one of his books to get a real appreciation).To get a random number that was unique me.to.you willo need to generate from a single source. However as he has not told us the context of useage this is a guess.
PurplePilot