How to echo random data

59 views Asked by At

I have the following code, that outputs all data from the comment field, however i wish for it to output only two and for them to be random, how can i got about doing this? many thanks.

$query = mysql_query("SELECT * FROM comments  ");

//query the database
echo "<b>Reviews</b> ";
WHILE($rows = mysql_fetch_array($query)):
$comment_by = $rows['comment_by'];
$comment= $rows['comment'];

echo "<div style ='font:14px/21px Arial,tahoma,sans-serif;color:#cf5c3f            </h>'>$comment_by</h>";
echo "<div style ='font:14px/21px Arial,tahoma,sans-serif;color:#ff0000 <h></h>'>$comment<br><br>";

 endwhile;
             ?>
2

There are 2 answers

1
Jason OOO On

Use:

SELECT * FROM comments
ORDER BY RAND()
LIMIT 2

LIMIT 2: for two records

and

ORDER BY RAND(): for random comments

See official MySQL documentation:

0
nicowernli On

From dev.mysql.com

$query = mysql_query("SELECT * FROM comments ORDER BY RAND() LIMIT 2");