...Beauty, cleaning, DIY tips and more - free to join!
   Login   Contact us   Site map   Puzzle Club   Ask a question    Newsletter

I need to select a row at random from my mySQL table. How do I do this?

Answered by: Dan Moore, web design expert

There are many ways to achieve this. However the easiest way is to make use of the rand() function in your mySQL query, and to ensure you only return one row in your result set.

Thus if you wanted to obtain a random quote, with the field name quote, from a database table called quotes, you could do this:

$result = mysql_query("SELECT quote FROM quotes ORDER BY rand() LIMIT 1");

$the_random_quote = mysql_result($result, 0, 0);

And that's all there is to it - the variable $the_random_quote as the name suggests now contains a quote chosen at random from the database.

Simply substitute the field and table name with those used in your application.

Back to Questions in the Web Design Section

Back to Ask the Expert home page