Forum Moderators: coopster
I've been trying to figure out why the random # changes before the user inputs the answer.
The random #'s show up but when I input the answer, it always says wrong and gives me the next set of random #s as the correct answer.
<?php
$r1 = rand(1,10);
$r2 = rand(1,10);
$answer=$r1+$r2;
?>
<form action="1math.php" method="post">
<?php
$show="$r1 + $r2 = ";
echo $show;
?>
<input type="text"name="answer" /><p></p>
<input type="submit" name="snd_answer" value="send answer" />
</form>
<?php
if (isset($_POST['snd_answer']))
{$a = $_POST['answer'];
echo "User ..$a";
echo "Random .. $answer";
if($answer==$a)
{echo"Great!";}
else
{echo "Sorry";
}}
else {echo 'Give it a try :)';}
?>
Thanks a bunch!
KP
When you submit the form, it basically refreshes your pages and since the script generates new random numbers at the start of the file, is your answer incorrect.
This could be one solution:
<?phpif (isset($_POST['snd_answer']))
{
// form is submitted, get old values
$r1 = $_POST["r1"];
$r2 = $_POST["r2"];settype($r1, "integer");
settype($r2, "integer");$answer = $r1+$r2
$a = $_POST['answer'];
if($answer==$a)
{
echo"Great!";
}
else
{
echo "Sorry. Try again.";
}} else {
// you haven't submitted the form, so generate a new
// answer
$r1 = rand(1,10);
$r2 = rand(1,10);
echo 'Give it a try :)';
}
?><form action="1math.php" method="post">
<input type="hidden" name="r1" >
value="<?php print $r1?>" />
<input type="hidden" name="r2"
value="<?php print $r2?>" />
<input type="text"name="answer" /><br>
<input type="submit" name="snd_answer"
value="send answer" />
</form>
I'm not sure if the settype() is necessary. I haven't tested this so it may have some flaws.
Hope this helps.