NYCPHP Meetup

NYPHP.org

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

Fernando Gabrieli fgabrieli at gmail.com
Wed Mar 11 17:01:17 EDT 2009


dont forget that md5($anyString) can return two hashes with the same value
(if you have a db with 1,000,000 entries using this, it may happen)

best,
fernando

On Wed, Mar 11, 2009 at 5:12 AM, Artur Marnik <artur at marnik.net> wrote:

> 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
>
>
>
>
> _______________________________________________
> New York PHP User Group Community Talk Mailing List
> http://lists.nyphp.org/mailman/listinfo/talk
>
> http://www.nyphp.org/show_participation.php
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.nyphp.org/pipermail/talk/attachments/20090311/acf846a9/attachment.html>


More information about the talk mailing list