想显示调用相同的随机值

时间:2015-03-30 16:18:20

标签: php html sql

我正在进行一项在线测验,其中包含id opt1-opt4并在数据库中回答。

我使用函数

调用问题
$con = mysql_connect("localhost", "ashu","ashua");
$db=mysql_select_db("quiz",$con) or die(mysql_error());

$display = mysql_query("SELECT * FROM quiz ORDER BY rand() LIMIT 2");

if (empty($_POST['submit'])) {


echo "<form method=post action=".$_SERVER['PHP_SELF'].">";
echo "<table border=0>";

while ($row = mysql_fetch_array($display)) {

$id = $row["id"];
$question = $row["question"];
$opt1 = $row["opt1"];
$opt2 = $row["opt2"];
$opt3 = $row["opt3"];
$opt4 = $row["opt4"];
$answer = $row["answer"];

echo "<tr><td colspan=3><br><b>Q:$question</b></td></tr>";
echo "<tr><td><input type=radio name=q$id value=\"$opt1\">$opt1 </td></tr>";
echo"<tr><td> <input type=radio name=q$id value=\"$opt2\">$opt2     </td></tr>";
echo "<tr><td><input type=radio name=q$id value=\"$opt3\">$opt3 </td></tr>";
echo "<tr><td><input type=radio name=q$id value=\"$opt4\">$opt4 </td></tr>";

}

echo "</table>";
echo "<input type='submit' value='See how you did' name='submit'>";
echo "</form>";

}

现在我想为答案显示相同的随机值,但我无法调用相同的随机值。 答案的功能是

$display = mysql_query("SELECT * FROM quiz ORDER BY id");

while ($row = mysql_fetch_array($display))
{

$question = $row["question"];
$answer = $row["answer"];
 $q = $_POST["q$id"];

echo "<tr><td><br>$question</td></tr>";

if ($q == $answer) 
    {
    echo "<tr><td>&raquo;You answered $q, which is correct</td></tr>";
    }
elseif ($q == "") {
echo "<tr><td>&raquo;You didn't select an answer. The Correct answer is $answer</td>     </tr>";
}
else {
echo "<tr><td>&raquo;You answered $q. The Correct answer is $answer</td></tr>";
}

}
echo "</table></p>";



}

如何在php中获取相同的随机值 这显示了数据库中的所有问题,我只想显示随机生成的那些

1 个答案:

答案 0 :(得分:0)

显示问题的精确而简短的解决方案是将所有问题存储在数组中,然后使用数组shuffle()array_rand()函数对数组进行随机播放或randing。

以下是您可以在案例中使用的shuffle()示例。

在你的while{}循环中,将所有$ question = $ row [“question”]放入数组中

$randomize_questions = array($question);

shuffle($randomize_questions);

print_r($randomize_questions); //this will put all the questions in a random order

然后您可以回显$randomize_questions

中的值