Jump to content

Random Results With 'SELECT * FROM xtable ORDER BY RAND(NOW()) LIMIT 1


xProteuSx

Recommended Posts

I guess that this used be to a standard line of code for producing random results/rows from a table:

 

$query = 'SELECT * FROM xtable ORDER BY RAND(NOW()) LIMIT 1';

 

However, it does not create random results since some update to MySQL.  I guess this used to work on older versions.  If I call this query up 5 times, I will get the same row 5 times.  Here is my code:

 

for ($x = 1; $x <= 5; $x++)
{
$query = 'SELECT * FROM mcat ORDER BY RAND(NOW()) LIMIT 1';
$result = mysql_query($query) or die ('Error in query: ' . mysql_error());

if (mysql_num_rows($result) > 0)
	{
	while($row = mysql_fetch_row($result))
		{
                        echo '<br>' . $row[0];
                        }
                 }
        }

Because this 'for' loop is set to run 5 times, I should get five different results for $row[0] unless the same row is chosen each time.  Even though I have over 50 rows of data, whichever row is selected first will reappear the following 4 times as well.

 

What am I doing wrong?  What can I do to get actual random results for each loop?

Depending on how quickly your script runs, NOW() may return the same value -- as I indicated in the other thread that you started, you're seeding rand() -- don't do that and you'll be fine.  But LIMIT 5 will save you the trouble of the extra loop!!!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.