如何从数据库中随机检索问题? [英] how to randomize retrieval of question from database?

查看:59
本文介绍了如何从数据库中随机检索问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.i具有以下代码:

<?
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个,单击下一步按钮,将显示下一个5个.预先感谢!

.the code above displays all the questions and their corresponding choices of answers which are retrieved from the database. my question is, how do you randomize the display of questions and display only 5 at a time and upon clicking a next button the next five will be displayed. Thanks in advance!

推荐答案

您可以使用LIMIT m,n来限制获得的结果数量,并以给定的数量抵消结果.

You can use LIMIT m,n to both limit the number of results you get and offset the results by a given amount.

现在您可以执行以下操作:

Now you could do something like:

 SELECT * FROM questions WHERE QuizID=1 LIMIT $page,5;

根据$_GET变量计算$page的位置.但这不会解决您的随机性.

Where you calculate the $page based on a $_GET variable. But this won't solve your randomness.

您总是可以通过保存在会话中的给定密钥为 RAND($ key)播种,以便可以ORDER BY RAND($key)并使用上述限制技术.

You could always seed RAND($key) by a given key that you save in your session so you could ORDER BY RAND($key) and use the above limit technique.

最简单的实现可能是获取整个结果集,对其进行洗礼并对其进行缓存.然后使用php仅显示缓存的特定块.

Probably the simplest to implement would be to get the entire result set, shuffle it and cache it. Then use a php to show only a specific chunk of the cache.

因为这与分页有关.让我告诉您,LIMIT m,n可能不像听起来那么快. 了解如何进行改进,并详细了解

Since this is related to pagination. Let me tell you, LIMIT m,n may not be as fast as it sounds. Learn how to improve it and read more about Efficient Pagination Using MySQL

这篇关于如何从数据库中随机检索问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆