.我有以下代码:
<?
session_start();
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';
mysql_connect($host,$user,$pw);
mysql_select_db($db);
$result = mysql_query("SELECT * FROM questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
$_SESSION['totalquestions']=$num_rows;
while($row = mysql_fetch_assoc($result))
{
$array[] = $row;
}
//Start the form
echo '<form method="post" action="result.php">';
for($i=0; $i<=($num_rows-1); $i++)
{
//Render a question + the answer choices
echo $array[$i]['Title']."<br />\n";
for ($j=1;$j<=4;$j++)
{
echo "<input type=\"radio\" name=\"ans$i\" value=\"$j\">".
$array[$i]['Answer'.$j]."<br />\n";
}
}
//End the form
echo "<input type=\"submit\" value=\"submit\" id=\"submit\">\n</form>";
?>
.上面的代码显示了从数据库中检索到的所有问题及其相应的答案选择。我的问题是,如何随机显示问题并一次只显示 5 个问题,然后在单击下一步按钮后将显示接下来的五个问题。提前致谢!
最佳答案
您可以使用 LIMIT m,n
来限制您获得的结果数量,并将结果抵消给定的数量。
现在你可以这样做:
SELECT * FROM questions WHERE QuizID=1 LIMIT $page,5;
根据 $_GET
变量计算 $page
的位置。但这不会解决你的随机性问题。
您始终可以通过保存在 session 中的给定 key 为 RAND($key) 播种,这样您就可以ORDER BY RAND($key)
并使用上面的代码极限技术。
可能最简单的实现方式是获取整个结果集,将其打乱并缓存。然后使用 php 仅显示缓存的特定 block 。
因为这跟分页有关。让我告诉你,LIMIT m,n 可能没有听起来那么快。 Learn how to improve it并阅读更多关于 Efficient Pagination Using MySQL 的信息
关于php - 如何随机从数据库中检索问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5686751/