Generating a random, unique code

Hi,

I am looking into some code that was done for our basket by someone else. I intend to use similar code myself in the new web site I am writing. it is pasted below.

I realise this bit of code generates the customer transaction code. But what makes it random and unique? Why has the web designer used rand twice? Surely once would be fine!? And also how does this code always remember the codes used previously? The current site does not use MySQL. It just uses PHP in the basket but I can see no way it ensures it is unique. We have not encountered a problem with uniqueness of customer transaction numbers, so how does it make sure of this — is it just lucky — is there more than can be done — particularly as the new site does use MySQL.

$VendorTxCode = "AGPS".(rand(0,32000)*rand(0,32000));

Matt.

so you can use that or an auto increment counter - whichever suits best.

Date time stamps don’t repeat. Not unless…deja vu all over again.

Exactly, so you can see straight away that the random number will not be unique especially as you approach the finite set of possibilities.

To generate a unique transaction code you need an auto incrementing counter of some sort - either in a database or some other kind of stored counter.

md5 on a date stamp?

it says nothing about uniqueness. in theory it could choose 876543 today and also 876543 in a years time too!! is this right?

Read through what rand() does and your questions should then be answered.

This is strongly not recommended. Use an auto increment primary key on the database table that stores the transactions. With 32 bit integers even if your system takes a transaction every second you won’t run out of id’s for 60 years, and I imagine by that time you can rewrite to 64 bit integers and then see you in a few million years.

Random transaction ids will, eventually, lead to a collision. Even if you use a hash function like md5 to create the string eventually you are going to get two data streams that create the same hash. When that happens your system will crash and it will be a royal pain in the a** to figure out why. The odds are extremely low, but they aren’t non-zero and never underestimate Murphy’s Law.

In short, don’t do it.