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开发者_如何学C it a primary key.
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.
I suppose you could trim a hash (md5() or sha1() etc.) of a field in the item to 8 characters- although you might end up with a collision.
Why not make the primary key field AUTOINCREMENT? Why does it need to be 8 alphanumeric characters?
You could probably use the uniqid
function.
But make sure you really want to do that. An AUTOINCREMENT
column might be a better solution.
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
精彩评论