user7133318 user7133318 - 1 year ago 108
PHP Question

PHP and MYSQL get random row in table

Hello I have the following code which returns the amount of rows in a table and the picks a random number between 1 and the amount of rows. I want to be able to get the row in the MySQL table that corresponds to the random number. So if the number is two, I want to get the second row down.
Here is my code so far:

$query = mysql_query("SELECT count(*) as total from videos");
$result = mysql_fetch_array($query);
$TotalCount = $result['total'];

$RandRow = mt_rand(1,$TotalCount);

I do have a id column but all the id's are not in order it goes like this for example: 4, 27, 43, 2, 18, 109, So i cant use that. How can I get a row in a table that corresponds to my random number?

Answer Source

You want one random row out of your table, right? Then you could use ORDER BY RAND() in your query and LIMIT 1. It sorts - surprise - randomly and only returns one dataset.


$query = mysql_query("SELECT * FROM videos ORDER BY RAND() LIMIT 1");

So you just have to do one query.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download