I want to write a php code that displays a random image and the person has to guess what it is. The problem is my php code tells me that the right city is incorrect, i cant figure out why
<?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>
The problem is your logic, you do not store the generated number that is used to show the image, instead you generate a new number every time you open the page.
You should store the generated number in (for example...) a session to preserve it and use that to compare.
Try it:
I hope it helps.
You're generating your random value EVERYTIME the page is loaded. e.g. when the person first visits it and gets the form, you generate
2
. When the form is submitted, you generate ANOTHER value, and this time it's3
. So even though the user correctly answers2
, you say they're wrong because the you've forgotten what you originally asked.You need to store the generated value somehow, and compare that to the response, e.g.
Add the following hidden field in your form, using
value="<?php echo $answer ?>"
and it will work with your present code.Matter 'o fact, you don't even need
name="correct_answer"
Just do:
Remember when you test this, you have a "1 in 3" chance for success!
Edit
Here's the code that I used: