Random number without repeting


#1

Hi, i need to generate a ramdom number and check if already exist on a row of one mysql table if exist generate another and check again and loop this until one unique set of numbers is generated.

$number = rand(0000,9999);
// here must check if already exist if yes then generate another and check again and again until one available is generated.

// save data
$query = “insert into datos
(number) values
(’$number’)”;
mysql_query($query) or
die (mysql_error());

Please help


#2

So what is the question?


#3

How must be the code to do that?


#4

maybe something like:

Psuedocode:

notFound = true
while (notFound)
{
    generate the number
    check if number is in DB (Hint SELECT, WHERE)
    if no records are returned
    {     
        notFound = false
    }
}

#5

I would also consider how many numbers are to be submitted in the table and how many numbers already exisit. I say this because if the number is LARGE (potentially up to 10000 entries based soley on the rand() function) then it might be more prudent to do an initial query of all the entries to be compared against, then create an array to search. As new numbers are developed they can be added to the array. Once all the new numbers are determined, then do the insert(s).