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

3
  • 6
    why cant you use an autoincrement? Also, which of those have you checked before asking: stackoverflow.com/search?q=random+number+mysql and why didnt they solve your problem? Commented Jan 12, 2012 at 11:47
  • 1
    if you can't use auto increment,can it be a string? Commented Jan 12, 2012 at 12:02
  • 1
    Take a look at this question on the birthday paradox for some discussion about PRNGs and uniqueness of random numbers. Commented Jan 12, 2012 at 12:23

4 Answers 4

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 

?>

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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"

2 Comments

Thanks, was thinking about something like that while writing the question. Gonna try it out asap.
Have you heard about the WHERE clause?
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

4 Comments

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.
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
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.
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.