tags:

views:

54

answers:

2
for($j = 0 ; $j < 87; $j++){

     echo $j.'<br/>';
     $unique = mt_rand(0,100000000);

    $insert_data = 'INSERT INTO uniques(uniq) VALUES ("'.$unique.'")';

        mysqli_query($conn , $insert_data);

        echo $unique.'<br />';

}

I just want to insert random number into table uniques. But something wrong with above code.It worked fine when total loop under 86 and got twice insert when looping above 86.

Thank you very much!

I don't mean I got duplicate random number. But it seems the "INSERT INTO" run twice in my php code!

+1  A: 

mt_rand(0,100000000) just returns a random number between 1 and 100000000 it does not keep track of the previously generated random numbers hence you can get duplicates.

If you want to make sure that you only insert unique values in the DB, you'll have to keep the history of the generated random numbers and keep calling mt_rand till you get a unique one.

codaddict
+1  A: 

As you need unique numbers, you may find the samples here of help

http://www.php.net/manual/en/function.mt-rand.php#83365

Alternately you could use a where clause to avoid duplicates, but this could be slow if you are adding a large number of records.

Jane T