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();
$tid = mt_rand(2,$max); # get random number between 2 and max (inc)
$result = mysql_query("SELECT tip FROM tips WHERE tid=$tid");
<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>$seed = time();
I tested your code and the problem seems to lie there. It just doesn't give a good seed to the random number generator. Try this instead:
<BLOCKQUOTE><font size="1" face="Verdana, Arial">code:</font><HR><pre>mt_srand((double)microtime()*1000000);[/code]
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.
Helping Small Business Grow Online!
I've switched the seeding function and it is working a lot better now -- thanks.
Using mySql's build in rand() didn't seem like a good choice, because I am looking for random values within specific ranges, depending on the context.