kush
kush

Reputation: 93

Generating Random Numbers as primary key In PHP / Mysql

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.

Upvotes: 0

Views: 3929

Answers (4)

fyr
fyr

Reputation: 20859

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.

Upvotes: 3

sagi
sagi

Reputation: 5737

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

Upvotes: 0

Mat
Mat

Reputation: 206689

You could probably use the uniqid function.

But make sure you really want to do that. An AUTOINCREMENT column might be a better solution.

Upvotes: 1

Chris
Chris

Reputation: 981

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?

Upvotes: 1

Related Questions