I am trying to pick out a random record from a table. I am using the build in RNG mt_rand() (I have also tried rand()) but keep getting the same 'random' number...
I know all about the inherent weaknesses of RNG functions, BUT, in more than 50 runs, I have gotten the same record each time, so clearly something is wrong.
This is the code I am using:
$sql = "SELECT tid FROM tips";
$result = mysql_query($sql);
$max = mysql_num_rows($result);
$seed = time();
mt_srand($seed);
$tid = mt_rand(2,$max); # get random number between 2 and max (inc)
$result = mysql_query("SELECT tip FROM tips WHERE tid=$tid");
Instead of generating a random number in PHP, just get MySQL to pick a random record for you. On versions 3.23.3 or later, you can use ORDER BY RAND() to do this:
SELECT ... FROM tblName ORDER BY RAND() LIMIT 1
On earlier versions of MySQL, you'll need to use a sneaky trick to do it. You might think to use RAND() as a column and then sort on that column as follows:
SELECT ..., RAND() AS RAND_NUM FROM tblName ORDER BY RAND_NUM LIMIT 1
However, MySQL sees that the RAND_NUM column is a single function call and assumes that it will have the same constant value for all rows. To optimize the query, it thus just picks a single random number -- ruining your random sort! To fool MySQL into calculating a random number for each row, you need to use RAND() in an expression. For example:
SELECT ..., (ID*0)+RAND() AS RAND_NUM FROM tblName ORDER BY RAND_NUM LIMIT 1
This query will output a randomly-chosen record from the table each time it is executed.
Bookmarks