Jump to content

Check for existence of a random number


NLCJ

Recommended Posts

Hello,

I'm currently creating a little script, and want to assign a random number to a row in the MySQL table as soon as it will be inserted. But that number may not have been used before. How will I do this?

 

I tried if else thingies, but then the code would be very long (just in case it randomly picks 10 times after each other a number that exists).

$randomnumber = rand(10000000, 99999999);
if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) {
  $randomnumber = rand(10000000, 99999999);
  if(mysql_num_rows(mysql_query("SELECT * FROM table WHERE randomnumber='".$randomnumber."')) == 1) {
    $randomnumber = rand(10000000, 99999999);
  }else {
   // Insert into database
  }
}else {

// Insert into database
}

 

I hope you understand my problem.

 

Regards,

Link to comment
https://forums.phpfreaks.com/topic/210706-check-for-existence-of-a-random-number/
Share on other sites

You will be better off grabbing all current random numbers first and putting them into an array.

$sql = 'SELECT randomnumber FROM table';
$result = mysql_query($sql);
$randomNumbers = array();

while(list($number) = mysq_fetch_row($result))
    $randomNumbers[] = $number;

 

Now we'll create a (recursive) function for generating the next random number, we'll pass the $randomNumbers array to this function. Within this function we'll generate a new random number and see if it is already in the $randomNumber array. If the number has not been picked we'll return the new number, otherwise we'll call the function again until a unique random number has been generated.

function randNumber(&$randomNumbers)
{
     // generate the new number
     $newNumber = rand(10000000, 99999999);

     // check to see if this number has been picked before
     if(in_array($newNumber, $randomNumbers))
    {
        // this number has already been picked, call the function again
        return randNumber($randomNumbers);
    }
    // number is unique, return this number
    else
    {
         return $newNumber;
     }
}

// call the function
$number = randNumber($randNumbers);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.