I am trying to write a php / mysql script that will pull 5 random records from the DB and display them. At the moment I am using the following to pull one record out and display it in a module, but im not sure how to pull out 5 at a time only. I will have approx 200-300 records in the DB in total.
I am currently using the following code to pull the single record out at random :
$result = mysql_query("SELECT * FROM `zgjzb_chronoforms_data_submitbusiness` ORDER BY RAND() LIMIT 0,4;");
$row = mysql_fetch_array($result);
?>
解决方案
You don't want to use ORDER BY RAND(). MySQL has to build a temporary table. If your table has a unique id column, something like this is much better:
SELECT * FROM `zgjzb_chronoforms_data_submitbusiness`
WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` )
ORDER BY id LIMIT 1;
See this blog post for other approaches that work well in php.