1

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?

2 Answers 2

1

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.

e.g.

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

So you just have to do one query.

Sign up to request clarification or add additional context in comments.

Comments

0
$query = mysql_query("SELECT id from videos"); 
$ids = array()
While($row=mysql_fetch_array($query)){
$ids[] =$row['id']
}
$RandRow = array_rand($ids,1);

You can fetch all rows ids as an array and select a random one from array by array_rand

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.