如何从DB同时随机显示一行。一切正常,但显示所有行。感谢
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
答案 0 :(得分:0)
您可以使用PHP执行此操作:
....
shuffle($rows);
$randomRow = reset($rows);
....
但更好的方法是更改SQL查询:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
答案 1 :(得分:0)
更改您的SQL请求:
SELECT id,name FROM table ORDER BY RAND()LIMIT 1;
答案 2 :(得分:0)
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
通过在sql查询中添加ORDER BY RAND(),您要求MySQL随机对结果进行排序,然后在LIMIT中限制您想要返回的行数。
示例代码基于选择单行编写。如果你想要更多,例如5,你需要添加一个while循环。