NYCPHP Meetup

NYPHP.org

[nycphp-talk] generate random unique 8-digit number

Artur Marnik artur at marnik.net
Wed Mar 11 04:12:04 EDT 2009


Joey Derrico wrote:
> One possibility would be to make a DB table with 2 columns. One where 
> each row has a value from 00000000 through 99999999, and the other 
> column marked as for used. When you need to generate the random number 
> you can query the database for each # not currently used and select 
> randomly from the values not in use and just update the DB to mark it 
> as used so it won't come up again. You won't have repeating numbers 
> then. However it will slow down your application because that is a lot 
> of rows to go through.
>
> Joey Derrico

actually query like:
select id, rand_number from rand_numbers where used = '0' limit 1;
and then:
update rand_numbers set used = '1' where id = '$row['id']'

will be very fast even if table has millions of entries
only generating the numbers will be slow but you have to run it only once

also make sure to lock the table before and unlock after so you don't 
have two users selecting the same entry

this solution is good only if you know how many random number you will need
another way is to use two tables - prefix and then rand_numbers
prefix has only one entry and you concat it with value selected from 
second table
after you run out of random numbers you just have to empty 
random_numbers table and regenerate values and change prefix to 
something else

but it is all complicated and I will just use old good 
md5(uniqid(rand(), true)) if possible

Artur






More information about the talk mailing list