How to generate a random but unique number and display this number in the source of my image tag


I have done some searching but really haven't found what I'm looking for. What I would like to do is generate a random BUT unique 5 digit number and push whatever number into an img tag on my page.

For example when people come to my page this number would generate and get pushed into this image tag:

<img src="" height="1" width="1" />

I have a mySQL DB and am looking to do this in PHP.



If you want to circumvent caching, as Red Filter says, better use the current timestamp.

If you really want a unique 5-digit number, you would have to keep track of which numbers you've used in the past. You could use a simple database for this. You create a random number using rand() or, according to the manual, better, mt_rand(), and then query whether it has already been used:

 SELECT FROM mytable WHERE random_number = '$random_number'

repeat until the query returns zero records.

Then, use the number and insert it into a database record:

 INSRT INTO mytable (random_number) VALUES ('$random_number');

If you don't lock the table while you write into it, there is the microscopic possibility of a collision (i.e. two instances of the same script ending up with the same number, and inserting the record, at the same time) but unless you have really massive numbers of requests, I think you can gracefully ignore this.