As a learning exercise I'm crating a simple math game now I already have the basics figured out but there is one stubborn problem that I can't figure out how to solve when I hit the submit button I always get the same response my answer is incorrect even if the answer given was correct.
Now if I'm understanding what is going on correctly when I hit the submit button a page reload is triggered and upon page reload a new question is generated so when I try to check the players response against the answer naturally the 2 no longer match and therefore I get the incorrect answer response regardless of whether the answer was correct or not
So my question is how do I store the answer to the question ? here is what I have so far
Code: Select all
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Math Madness</title>
</head>
<body>
<form action="question.php" method="post" name="math_madness">
<p><?php echo $question; ?>
<br><input type="text" name="answer">
<br><?php echo $message; ?></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
Code: Select all
<?php
//define and set variables
$responce = $_POST['answer'];
$message = "";
$value_1 = rand(1,1000);
$value_2 = rand(1,1000);
$value_3 = rand(1,4);
switch ($value_3)
{
case 1:
$question = "What is" ." ". $value_1 . " / " . $value_2 . " ? ";
$answer = $value_1 / $value_2;
break;
case 2:
$question = "What is" ." ". $value_1 . " * " . $value_2 . " ? ";
$answer = $value_1 * $value_2;
break;
case 3:
$question = "What is" ." ". $value_1 . " + " . $value_2 . " ? ";
$answer = $value_1 + $value_2;
break;
case 4:
$question = "What is" ." ". $value_1 . " - " . $value_2 . " ? ";
$answer = $value_1 - $value_2;
break;
}
//check if the submit button has been pressed.
if(isset($_POST['submit']))
{
if($responce !== $answer)
{
$message = "Incorrect";
}
else
{
$message = "Correct";
}
}
?>