我想写一个显示随机图像的php代码,这个人必须猜测它是什么。问题是我的php代码告诉我正确的城市不正确,我不知道为什么
<?php
$random = rand(1, 3);
$answer ;
if ($random == 1) { $answer = "chicago" ;}
elseif($random == 2) {$answer = "LA" ;}
elseif($random == 3) {$answer = "NewYork" ;}
else {echo "Answer is None" ; }
if (isset($_POST["choice"])) {
$a = $_POST["choice"];
if($a ==$answer){
echo "<br> working <br>" ;
}else {echo "<br> Not Working <br>";}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>City Guess</title>
</head>
<body>
<center>
<img src="four/Image_<?php echo $random ;?>.jpg" width="960" height="639" alt=""/>
<form action="" method="POST">
chicago <input type= "radio" name="choice" value="chicago" />
<br>
LA <input type= "radio" name="choice" value="LA" />
<br>
NewYork <input type= "radio" name="choice" value="NewYork" />
<br>
<input type ="submit" value="Submit" />
</form>
</center>
</body>
</html>
您正在生成随机值 每次加载页面时。 例如,当该人第一次访问它并获取表单时,您会生成2
。提交表单时,您会生成另一个值,这次是3
.因此,即使用户正确回答2
,您说他们错了,因为您忘记了最初问的内容。
您需要以某种方式存储生成的值,并将其与响应进行比较,例如
$rand = rand(1,3);
<input type="hidden" name="correct_answer" value="$rand">
if ($_SERVER["REQUEST_METHOD"] == 'POST') {
if ($_POST['correct_answer'] == $_POST['user_answer']) {
echo 'correct';
}
}
问题是你的逻辑,你不存储用于显示图像的生成的数字,而是在每次打开页面时生成一个新数字。
您应该将生成的数字存储在(例如...)会话中以保留它并使用它来进行比较。
试试看:
$random = floor(rand(1, 4));
我希望它有所帮助。
使用 value="<?php echo $answer ?>"
在表单中添加以下隐藏字段,它将与您当前的代码一起使用。
<input type="hidden" name="correct_answer" value="<?php echo $answer ?>">
事实上,你甚至不需要name="correct_answer"
只需做:
<input type="hidden" value="<?php echo $answer ?>">
请记住,当您对此进行测试时,您有"三分之一"的成功机会!
<小时 />编辑
这是我使用的代码:
<?php
$random = rand(1, 3);
$answer;
if ($random == 1) { $answer = "chicago" ;}
elseif($random == 2) {$answer = "LA" ;}
elseif($random == 3) {$answer = "NewYork" ;}
else {echo "Answer is None" ; }
if (isset($_POST["choice"])) {
$a = $_POST["choice"];
if($a ==$answer){
echo "<br> working <br>" ;
}else {echo "<br> Not Working <br>";}
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>City Guess</title>
</head>
<body>
<center>
<img src="four/Image_<?php echo $random ;?>.jpg" width="960" height="639" alt=""/>
<form action="" method="POST">
<input type="hidden" value="<?php echo $answer ?>">
chicago <input type= "radio" name="choice" value="chicago" />
<br>
LA <input type= "radio" name="choice" value="LA" />
<br>
NewYork <input type= "radio" name="choice" value="NewYork" />
<br>
<input type ="submit" value="Submit" />
</form>
</center>
</body>
</html>