我想在PHP中进行测验。 答案从单选按钮中选择。如果用户选择正确答案,则如果错误答案他的分数减1,则他的分数加1。 最后,我希望他的分数显示为警报。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quiz</title>
</head>
<body>
<?php
$score=0;
?>
<p><font size="3"> <b>There is 2 multiple choice questions<br />
Every correct answer +1 <br />
Wrong answer -1<br />
Good Luck!</b></font></p></br></br></br>
<table width="300" border="1" cellspacing="2" cellpadding="2">
<tr>
<td><p><font size="3"> <b> Question 1:
</b></font></p>
Guess The Star Of The Movie <font color="red">"The Equalizer"</font><br />
<br />
<input type="radio" name="n1" value="Denzel Washington">Denzel Washington<br>
<input type="radio" name="n1" value="Mark Wahlberg">Mark Wahlberg<br>
<input type="radio" name="n1" value="Jason Statham">Jason Statham<br>
<input type="radio" name="n1" value="Sylvester Stallone">Sylvester Stallone<br>
</form ></td>
</tr>
<tr>
<td><p><font size="3"> <b> Question 2:
</b></font></p>
Guess The Star Of The Movie <font color="red">"Game Plan"</font><br />
<br />
<input type="radio" name="n2" value="Vin Diesel">Vin Diesel<br>
<input type="radio" name="n2" value="Dwayne Johnson">Dwayne Johnson<br>
<input type="radio" name="n2" value="Liam Hamworth">Liam Hamworth<br>
<input type="radio" name="n2" value="Adam Sandler">Adam Sandler<br>
</form ></td>
</tr>
</table>
<?php
$score=0;
if($n1=="Denzel Washington")
$score = $score+1;
else $score = $score-1;
if($n2=="Dwayne Johnson")
$score = $score+1;
else
$score = $score-1;
?>
<button type="button" onclick="alert('<?php echo "your score is: ".$score.""; ?> ')">Submit</button>
</body>
</html>
当我点击提交按钮时,分数为-2,尽管我选择了正确的答案
答案 0 :(得分:1)
您的代码无条件运行,无论何时加载页面。这意味着你的答案是正确的#34;代码总是声明错误。你有效地得到了:
$score = 0;
$score = $score - 1; // $n1 is blank, therefore wrong
$score = $score - 1; // $n2 is blank, therefore wrong
您应该至少检测表单是否实际提交,例如
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... do scoring here ..
}
但大多数情况无关紧要。您甚至没有<form>
标记,因此这些输入字段无法提交任何内容。