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?

Link to comment
Share on other sites

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!!!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.