Php Random Number Not Working
Solution 1:
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's 3. So even though the user correctly answers 2, 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.
$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';
}
}
Solution 2:
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.
Solution 3:
Try it:
$random = floor(rand(1, 4));
I hope it helps.
Solution 4:
Add the following hidden field in your form, using value="<?php echo $answer ?>" and it will work with your present code.
<inputtype="hidden"name="correct_answer"value="<?phpecho$answer?>">Matter 'o fact, you don't even need name="correct_answer"
Just do:
<inputtype="hidden"value="<?phpecho$answer?>">Remember when you test this, you have a "1 in 3" chance for success!
Edit
Here's the code that I used:
<?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><metacharset="utf-8"><title>City Guess</title></head><body><center><imgsrc="four/Image_<?phpecho$random ;?>.jpg"width="960"height="639"alt=""/><formaction=""method="POST"><inputtype="hidden"value="<?phpecho$answer?>">
chicago <inputtype= "radio"name="choice"value="chicago" /><br>
LA <inputtype= "radio"name="choice"value="LA" /><br>
NewYork <inputtype= "radio"name="choice"value="NewYork" /><br><inputtype ="submit"value="Submit" /></form></center></body></html>
Post a Comment for "Php Random Number Not Working"