如何编写在线测验项目代码

时间:2011-10-26 22:04:39

标签: php

$answers=array();
$rightanswer=array();
echo '<form action="question_check.php" method="post">';
$result=mysql_query("select * from sual where sual_id='1'");

if(mysql_num_rows($result))
{
    $row=mysql_fetch_row($result);
{
$question_id=$row[0];
$question=$row[1];
$answers[0]=$row[2];
$answers[1]=$row[3];
$answers[2]=$row[4];
$rightanswer=$row[4];

$rand_keys=array_rand($answers,3);
$answer0=$answers[$rand_keys[0]];
$answer1=$answers[$rand_keys[1]];
$answer2=$answers[$rand_keys[2]];



echo "question:".$row[1]."<br>";
echo '<input type="radio" value="'.$answer0.'">'.$answer0."<br>";
echo '<input type="radio" value="'.$answer1.'">'.$answer1."<br>";
echo '<input type="radio" value="'.$answer2.'">'.$answer2."<br>";
echo '<input type=hidden value="'.$rightanswer.'">';
echo '<input type="submit" value="answer">';echo '<input type="reset" value="sil">';
}

}
echo "</form>";

我想创建在线考试项目。但是有一个问题。我写了一个问题_check.php页面,但它不起作用,我该怎么写呢。上面的代码是我的index.php ...问题是我不确切知道如何将我选择的答案与数据库中的正确答案进行比较..请帮助我enter code here

1 个答案:

答案 0 :(得分:3)

您不希望为正确答案添加隐藏值,因为任何人都可以查看来源。 你想添加一个参数&#39; name&#39;到您的单选按钮并包含问号的隐藏值,以检查它在check_value.php中的正确值。在您的示例中,您执行SELECT * // WHERE sual_id = 1;我假设id与问题编号有关。 此外,您应该将单选按钮的值定为0,1,2,而不是将整个字符串存储在那里,因为比较字符串需要更长的时间。

<input type="radio" name="answer" value="'.$answer0.'">'.$answer0."<br>";
<input type="radio" name="answer" value="'.$answer1.'">'.$answer1."<br>";
<input type="radio" name="answer" value="'.$answer2.'">'.$answer2."<br>";
<input type="hidden" name="question_number" value="'.$question_number.'" />

发布到question_check.php时,您可以访问$ _POST [&#39; answer&#39;]和$ _POST [&#39; question_number&#39;]。

if(isset($_POST['answer']) && isset($_POST['question_number']))  {
$answer=$_POST['answer'];
$question_number=$_POST['question_number'];

$result=mysql_query("select 'rightanswer' from sual where sual_id='$question_number'");

if(mysql_num_rows($result))
{
$row=mysql_fetch_row($result);
if($row[0]==$answer){
//correct answer
//$answer_result++;
}

else  {
//$answer_result--;
}
}

}
else  {
//no answer and a question number was posted
}
编辑:另外我同意你应该研究一下PDO(php数据对象),因为它的参数化查询(SELECT something FROM some where where where = =)可以绑定到变量,它背后的机制将呈现SQL注射攻击无用。 永远不要相信用户!