g0dl3ss g0dl3ss - 4 months ago 13
MySQL Question

How generate UNIQUE random number in php

Possible Duplicate:

Algorithm for generating a random number

Hi i need to assign a randomly generated number to some entries into the database and it must be unique.
I use:

$random_number = mt_rand();
mysqli_query($db_connection, "INSERT INTO my_table (rand_num, blabla) VALUES ('$random_number', '$blabla')");

But ofc there could always be a slightly low chance that 2 random numbers will be the same.
Then i could do something like:

function random_check($random_number) {
$random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
$result = 1;
while($row = mysqli_fetch_array($random_check)){
if ($row['rand_num'] == $random_number) {
return $result;

$random_number = mt_rand();
$random_check = random_check($random_number);
if ($random_check == 0) {
$random_number = mt_rand();

But this would only check the number once and there will still be a chance that the new generated number already exists into the db.

Any suggestions?


Here is a method which you can use:

$num= mt_rand();
$con = mysql_connect("localhost","uname","password");
$sel_query  = "SELECT *  FROM  my_table WHERE rand_num =%d"; // query to select value 
$ins_query = "INSERT INTO my_table(rand_num) VALUES(%d)";    // query to insert value
$result =  mysql_query(sprintf($sel_query,$num),$con);
while( mysql_num_rows($result) != 0 ) {                      // loops till an unique value is found 
    $num = mt_rand();
    $result = mysql_query(sprintf($sel_query,$num),$con);
mysql_query(sprintf($ins_query,$num),$con); // inserts value