What is the best way to generate alphanumeric random number to 8 digit in php which is case sensitive? I want to use this unique number to be stored in mysql data base and make it a primary key.
-
1If it doesnt have to be alphanumeric limited to 8 digits, you could simply use an Auto-Incrementing Primary Key.Gordon– Gordon2011-07-16 09:17:02 +00:00Commented Jul 16, 2011 at 9:17
-
11) There is no reason to do this. 2) No one should help you because you accept NO answers.Michael B– Michael B2011-07-16 09:18:38 +00:00Commented Jul 16, 2011 at 9:18
-
possible duplicate of What is the best way to generate a random key within PHP?ypercubeᵀᴹ– ypercubeᵀᴹ2011-07-16 09:39:10 +00:00Commented Jul 16, 2011 at 9:39
-
This answer may be helpful too: stackoverflow.com/questions/307486/short-unique-id-in-php/…ypercubeᵀᴹ– ypercubeᵀᴹ2011-07-16 09:40:30 +00:00Commented Jul 16, 2011 at 9:40
4 Answers
Never use a random key as primary key. Primary keys need to be unique in most cases and random numbers are not.
E.g.
1 1 1 1 1 1 0 1
is also a valid output of a 8 digit random number generator.
You should use auto-increment fields or generators instead to make sure that your primary key is really unique.
If you want to have a identifier which is likely to be unique and some sort of random try to use mysql facilities like: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
A caveat might be to reiterate inserts multiple times.
4 Comments
You could probably use the uniqid function.
But make sure you really want to do that. An AUTOINCREMENT column might be a better solution.
Comments
Not random, but if you don't want your IDs to be sequential then perhaps you could encrypt them in some way. See the following question on the same topic: Simple integer encryption