1

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) {
    require_once('db_access.php');
    $random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
    mysqli_close($db_connection);
    $result = 1;
    while($row = mysqli_fetch_array($random_check)){
            if ($row['rand_num'] == $random_number) {
             $result=0
           }
    }
        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? Thanks

Community
  • 1
  • 1
g0dl3ss
  • 393
  • 1
  • 6
  • 19
  • 6
    why cant you use an autoincrement? Also, which of those have you checked before asking: http://stackoverflow.com/search?q=random+number+mysql and why didnt they solve your problem? – Gordon Jan 12 '12 at 11:47
  • 1
    if you can't use auto increment,can it be a string? – Umut Jan 12 '12 at 12:02
  • 1
    Take a look at [this question on the birthday paradox](http://stackoverflow.com/questions/2145510/python-random-is-barely-random-at-all) for some discussion about PRNGs and uniqueness of random numbers. – ConcernedOfTunbridgeWells Jan 12 '12 at 12:23

4 Answers4

2

Doing a SELECT rand_num FROM my_table and checking the resulting values is very, very inefficient. Use a WHERE clause:

do {
    $random_number = mt_rand();
    $query_object = mysqli_query($db_connection, "SELECT 1 FROM my_table WHERE rand_num = $random_number");
    $query_record = mysqli_fetch_array($query_object);
    if(! $query_record) {
        break;
    }
} while(1);

It is possible to write this code in lesser lines.

Salman A
  • 262,204
  • 82
  • 430
  • 521
2

Here is a method which you can use:

<?php
$num= mt_rand();
$con = mysql_connect("localhost","uname","password");
mysql_select_db("dbname",$con);
$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 

?>

muya.dev
  • 966
  • 1
  • 13
  • 34
Vijeenrosh P.W
  • 359
  • 1
  • 3
  • 8
0
function random_check($random_number) {
    require_once('db_access.php');
    $random_check = mysqli_query($db_connection, "SELECT rand_num FROM my_table");
    mysqli_close($db_connection);
    while($row = mysqli_fetch_array($random_check)){
            if ($row['rand_num'] == $random_number) {
             return false;
           }
    }
    return true;
};

while(!random_check(mt_rand()){
    $myNumbber = random_check(mt_rand();
}

--> Now u got unique number in "myNumber"

jeff
  • 21
  • 1
0
md5( strtotime("now").$_SERVER['REMOTE_ADDR'] );

strtotime("now") would give you a unique number, but ifyou are using this script to process forms/uploads etc from multiple users, the ip address will just make certain of that (on the off chance that at the exact same second two entries are made... can that even happen?? hmm...)

md5() cos i felt like it :D

Umut
  • 66
  • 6
  • mhm, yes, but two request hitting the server at the same second from the same IP will create the same random number then -> not unique. Multiple Users could be behind a proxy or one user could be double clicking. you could use microtime for more variance. oh, and md5 doesnt generate a number. – Gordon Jan 12 '12 at 11:57
  • aha, that makes sense.session id's come to mind... trying to make use of the already built in awesomeness of php as I could see a mysql loop based sollution being slow – Umut Jan 12 '12 at 11:59
  • since the number has to be unique in the table, it makes sense *not* to generate the number with php but inside mysql with respect to whats already in the table. otherwise you'll have to do multiple attempts at inserting when the number does already exists. roundtrips to the db are expensive. – Gordon Jan 12 '12 at 12:01
  • ok, I was thinking more like skipping any checks and validations and being able to rely 100% on the generated number being unique. This way you generate once, query once and move on. What do you reckon? – Umut Jan 12 '12 at 13:21