1

Would be awesome if you could help me out! I am trying to build a simple page to display random math questions. The answers should be typed in by the user and should be validated on the same page, giving him feedback on success and failure.

The problem is that by submitting the form input to the same page (I called it "form6.php") the page reloads and a new set of numbers is generated - that is why the "solution" variable is newly defined and cannot be used to test the accuracy of the user's answer.

This is the code I have so far (works fine for fixed numbers but fails with the random number generation):

<?php
$number1 = rand(1,100);
$number2 = rand(1,100);
$solution = $number1+$number2;

echo "$number1+$number2=?";

?>

<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">
</form>

<?php
if(isset($_POST['answer'])){
    if ($_POST["answer"] == $solution)
    {echo "That's right";}
    else
    {echo "That's wrong!";};
}

?>

Any help is highly appreciated! Since I am not a professional coder, the more specific you can get, the better!

Timothy Randall
  • 17,634
  • 1
  • 15
  • 27
user3261573
  • 89
  • 1
  • 1
  • 5
  • Is there such as thing as ` – Funk Forty Niner Feb 01 '14 at 23:10
  • @Fred -ii- `integer` is not quite right, but there is a solution in HTML5: http://stackoverflow.com/questions/8808590/html5-number-input-type-that-takes-only-integers – Sam Feb 01 '14 at 23:12
  • I did find something to that effect of `type="number"`, but not "integer". Thanks @SamSullivan One could use `(int)` in PHP though, which maybe the OP or where he/she got the code from. – Funk Forty Niner Feb 01 '14 at 23:13
  • Sidnote: Seeing you have your code all in one big clump, you'll want to change `action="form6.php"` to `action=""` and if that's not the case, do split up your code to indicate what's in what file. Too much room for errors. – Funk Forty Niner Feb 01 '14 at 23:18

5 Answers5

2

A POSTed form will reload your PHP script, causing 2 new rand() numbers to be generated. You're going to want to pass the solution in the form.

Edit: I updated the answer to show a quick solution for using random operands for verification. This was simply done by switching through a random integer. Please note that when using - or / you may receive non-integer numbers (3 / 58 or 15 - 86), so you may want to add some custom logic to prevent this.

<?php
$number1 = rand(1,100);
$number2 = rand(1,100);

switch(rand(0,3)) {
    case 0:
        $solution = $number1 + $number2;
        echo "$number1+$number2=?";
        break;
    case 1:
        $solution = $number1 - $number2;
        echo "$number1-$number2=?";
        break;
    case 2:
        $solution = $number1 * $number2;
        echo "$number1*$number2=?";
        break;
    case 3:
        $solution = $number1 / $number2;
        echo "$number1/$number2=?";
        break;
}
?>

<form action="form6.php" method="post">
    Your Answer:<br><input type="integer" name="answer">

    <input type="hidden" name="solution" value="<?php echo $solution; ?>">
    <input type="Submit" value="Submit!">
</form>

<?php
if(isset($_POST['answer']) && isset($_POST['solution'])) {
    if ($_POST["answer"] == $_POST['solution']) {
        // Valid
    } else {
        // Incorrect
    }
}
?>
Sam
  • 20,096
  • 2
  • 45
  • 71
  • 1
    Sam! That's awesome. Such an easy solution, works great! Thanks a lot! – user3261573 Feb 03 '14 at 19:32
  • Just one last thing: How could I make it happen, that it would choose the operator for the calculations randomly (+,-,/,*)? A simple rand_array doesn't seem to work because then the operators would not be counted as operators - or I cannot display them as strings in the question on top. Would you use the eval() mechanism here? And if so, how? – user3261573 Feb 03 '14 at 22:20
  • @user3261573 updated my answer..please beware for non-integer answers. If I have helped, please select my answer :) – Sam Feb 03 '14 at 22:36
  • Again, I didn't know the solution. Hero level for SAM! :) Thanks! – user3261573 Feb 07 '14 at 18:22
  • Of course @user3261573 :), if you can accept the answer that would be great. – Sam Feb 07 '14 at 18:39
1

If you don't want to include the solution in your form (be it hidden), you have to store solutions in a separate text file in which you can, for instance, serialize your data.

Alternatively, you can use sessions or cookies.

But you have to store the solution somewhere.

Here is an attempt with sessions:

<?php
session_start();

$nb1 = rand(1,100);
$nb2 = rand(1,100);

$_SESSION['number1'] = $nb1;
$_SESSION['number2'] = $nb2;
$_SESSION['solution'] = $nb1 + $nb2;

// (...)

if(isset($_POST['answer']))
{
    if ($_POST["answer"] == $_SESSION['solution'])
        {echo "That's right";}
    else
        {echo "That's wrong!";};

    unset($_SESSION['nb1']);
    unset($_SESSION['nb2']);
    unset($_SESSION['nbsolution']);
}
Jivan
  • 21,522
  • 15
  • 80
  • 131
  • +1 for a solution with SESSION's. I didn't think it was necessary, since this seems like a pretty basic validation anyways..but its good to have the options. – Sam Feb 01 '14 at 23:29
  • Yeah, thanks, I am just starting with sessions, so good to know. Cheers! – user3261573 Feb 03 '14 at 19:32
0
if(isset($_POST['answer'])===true){
    if ($_POST["answer"] == $solution)
    {echo "That's right";}
    else
    {echo "That's wrong!";};
}

If you are using isset($_POST['answer']) you must include === true at the end Also make sure you use instead of integer.

TestUser1
  • 383
  • 1
  • 3
  • 14
  • This isn't the problem. `if` statements evaluate the expression to see if it equals `true` already. "If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it." http://www.php.net/manual/en/control-structures.if.php – Sam Feb 01 '14 at 23:14
  • `if (isset($_POST['answer']) === true)` is as useful as writing something like `if (true === true)` – Jivan Feb 01 '14 at 23:36
0

@user3261573,

As pointed out by @Sam, you could pass the value in a hidden field, but, as @Jivan said, a better approach would be using a session to store the solution.

Here's the code:

Ps.: I simplified the code for a better understanding.

<?php
    // Initiate session
    session_start();

    // If the FORM has been submited, verify answer
    if( isset($_SESSION['solution']) === TRUE && $_SESSION['solution'] !== NULL && isset($_POST['answer']) === TRUE && isset($_POST['solution']) == TRUE ){
        if( $_SESSION['solution'] == $_POST['answer'] ){
            echo 'That\'s right';
        }else{
            echo 'That\'s wrong';
        }
    }
    // If the FORM ain't submited yet, display the question
    else{
        // Random numbers
        $number1 = rand(1,100);
        $number2 = rand(1,100);

        // Store solution in session for further comparison
        $_SESSION['solution'] = $number1+$number2;

        // Echo question
        echo "$number1+$number2=?";


        echo '<form action="form6.php" method="post">
        Your Answer:<br>
        <input type="integer" name="answer">
        <input type="Submit" value="Submit!">
        </form>';
    }
?>

If you like it, here's a few tutorials on using PHP SESSIONs:

http://www.w3schools.com/php/php_sessions.asp http://www.php.net/manual/en/session.examples.basic.php

0
<?php
$number1 = rand(1,100);
$number2 = rand(1,100);

echo "$number1+$number2=?";

?>

<form action="form6.php" method="post">
Your Answer:<br>
<input type="integer" name="answer">
<input type="Submit" value="Submit!">

<input type="hidden" name="n1" value="$number1">
<input type="hidden" name="n2" value="$number2">
</form>

<?php
if(isset($_POST['answer'])){
    $solution = $_POST['n1'] + $_POST['n2'];
    if ($_POST["answer"] == $solution)
    {echo "That's right";}
    else
    {echo "That's wrong!";};
}

?>

john
  • 1