-1

I have the following code in file index.php:

include('db_connect.php'); //Here's the script that provides mysql connection to a database

$a = round(rand(1,100));
$b = round(rand(160,202));
$c = round(rand(50,110));
$d = round(rand(1,99999));

$sql = "INSERT INTO sInstance (p1,p2,p3,p4) VALUES ('".$a."','".$b."','".$c."','".$d."')";
$result = mysql_query($sql) or die(mysql_error());

Obviously, it randomly generates values and inserts them as a record into MyISAM database table sInstance.

The problem: after ~1000 records are generated & inserted, it's almost impossible to generate new records (with unique sets of values). Every new record is a clone of some old one (with the same p1-p2-p3-p4 values).

The question: How to avoid this and make php generate unique records?

The clue: It is a server-side problem with PHP, probably it somehow caches values that are set with the help of RAND() function. The problem is not connected neither to browser, nor to mysql itself.

Al D
  • 67
  • 5

3 Answers3

1

Not sure if you're not doing something wrong, but reseting the random seed generator will do the trick :

http://php.net/manual/en/function.srand.php

0

Try mt_rand() instead.

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

If that does not work, can you add the database schema?

0

The seeding for rand() happens using the current timestamp on the server, so when you rapidly generate random values, you might get the same seed for creating random values.

Are you sure it does not happen right away, and only after 1000 records or so?

You might consider using a better random number generator like mt_rand()

Roy B.
  • 41
  • 1
  • Yes, it happened when there're around 1000 records. I've also tried generating records in a cycle (for, while- and etc.), and had the same result. I also tried reseting PHP cache, MySQL cache and did lot's of other irrelevant stuf. mt_rand worked for me right as I wanted, thx. – Al D Aug 28 '13 at 14:01