0

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.

4

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

First, why never? Second, are there not random generators that yield unique output?
The design of a random number generator prevents the output of being unique.
Yes, but we can wrap it inside another generator that cuts non-unique output. Or try it anyway against the database until it is not already there (and thus accepted as primary key input). The OP's wording is not perfect but a unique random key is not unheard of.
@ypercube : it might be that the op meant this so i edited my post to add some more information regarding uuids.
1

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?

Comments

1

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.