Ok I am trying to make something to ask you random multiplication questions. Now it asks the questions fine. Generates the random questions fine. But when it reloads the page the random numbers are different…
how can I fix this?
<?php
$rndnum1 = rand(1, 12);
$rndnum2 = rand(1, 12);
echo "<h3>". $rndnum1 . " x ";
echo $rndnum2 . "</h3>";
if($_SERVER["REQUEST_METHOD"] == "GET") {
$answer=0;
}
else if($_SERVER["REQUEST_METHOD"] == "POST") {
$answer=trim($_POST["answerInput"]);
$check=$rndnum1*$rndnum2;
if($answer==$check) {
echo "Correct!";
}
else {
echo "Wrong!";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="answerInput" value="<?php echo $answer; ?>" size="20"/>
</td>
<td>
<?php echo $answerError; ?>
</td>
</tr>
<tr>
<td class="signupTd" colspan="2">
<input type="submit" name="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
When you reload the page, $rndnum1 and $rndnum2 are set to new random numbers via the rand() function. That’s why they are not staying the same. Try passing the original random numbers along with the POST, and calculate the numbers from $_POST before checking if the answer’s correct.
To do this, make sure you include the following line for both random variables in your submission form:
Then, on the next load of the page after the answer form is submitted, get the numbers with
$_POST['rndnum1'], etc.