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.

kush
  • 93
  • 2
  • 10
  • 1
    If it doesnt have to be alphanumeric limited to 8 digits, you could simply use an Auto-Incrementing Primary Key. – Gordon Jul 16 '11 at 09:17
  • 1
    1) There is no reason to do this. 2) No one should help you because you accept NO answers. – Michael B Jul 16 '11 at 09:18
  • possible duplicate of [What is the best way to generate a random key within PHP?](http://stackoverflow.com/questions/637278/what-is-the-best-way-to-generate-a-random-key-within-php) – ypercubeᵀᴹ Jul 16 '11 at 09:39
  • This answer may be helpful too: http://stackoverflow.com/questions/307486/short-unique-id-in-php/307773#307773 – ypercubeᵀᴹ Jul 16 '11 at 09:40

4 Answers4

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.

fyr
  • 20,227
  • 7
  • 37
  • 53
  • First, why never? Second, are there not random generators that yield unique output? – ypercubeᵀᴹ Jul 16 '11 at 09:26
  • The design of a random number generator prevents the output of being unique. – fyr Jul 16 '11 at 09:32
  • 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ᵀᴹ Jul 16 '11 at 09:37
  • @ypercube : it might be that the op meant this so i edited my post to add some more information regarding uuids. – fyr Jul 16 '11 at 09:52
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?

Chris
  • 981
  • 1
  • 11
  • 21
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.

Mat
  • 202,337
  • 40
  • 393
  • 406
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

Community
  • 1
  • 1
sagi
  • 5,619
  • 1
  • 30
  • 31