PHP随机数不起作用

时间:2014-04-01 14:51:56

标签: php html image random input

我想编写一个显示随机图像的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>

4 个答案:

答案 0 :(得分:2)

您正在生成随机值 EVERYTIME 页面已加载。例如当此人首次访问并获取表单时,您会生成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';
   }
}

答案 1 :(得分:1)

问题在于您的逻辑,您不存储用于显示图像的生成数字,而是每次打开页面时生成新数字。

您应该将生成的数字存储在(例如......)会话中以保留它并使用它进行比较。

答案 2 :(得分:0)

试一试:

$random = floor(rand(1, 4));

我希望它有所帮助。

答案 3 :(得分:0)

使用value="<?php echo $answer ?>"在表单中添加以下隐藏字段,它将与您现有的代码一起使用。

<input type="hidden" name="correct_answer" value="<?php echo $answer ?>">

事实上,你甚至不需要name="correct_answer"

只是做:

<input type="hidden" value="<?php echo $answer ?>">

请记住,当您对此进行测试时,您有“1/3”成功的机会!


修改

以下是我使用的代码:

<?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>