MozillaZine

PHP coding question

Discuss how to use and promote Web standards with the Mozilla Gecko engine.
Bethrezen
 
Posts: 375
Joined: September 13th, 2003, 11:56 am

Post Posted March 28th, 2017, 2:42 pm

Hi all

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";
    }
}
?>

malliz
Folder@Home

User avatar
 
Posts: 43194
Joined: December 7th, 2002, 4:34 am
Location: Australia

Post Posted March 29th, 2017, 12:05 am

You probably need to ask here
https://www.phpbb.com/
What sort of man would put a known criminal in charge of a major branch of government? Apart from, say, the average voter.
"Terry Pratchett"

Frenzie

User avatar
 
Posts: 2103
Joined: May 5th, 2004, 10:40 am
Location: Belgium

Post Posted March 29th, 2017, 3:02 pm

The first rule of debugging is to verify what's going on. In this case you want to know what $response actually is before you go assuming all kinds of things about it.

Use something like print_r($responce). (Btw, I'd correct that to response. :P) See http://php.net/manual/en/function.print-r.php

As to the problem at hand, since you're using a strict comparison I suspect the problem is simply that you're comparing a string to a number. You could either convert $responce to a number like $responce = (float)$responce or reduce the strictness by going for !=.
Intelligent alien life does exist, otherwise they would have contacted us.

Bethrezen
 
Posts: 375
Joined: September 13th, 2003, 11:56 am

Post Posted March 31st, 2017, 11:38 am

The first rule of debugging is to verify what's going on. In this case you want to know what $response actually is before you go assuming all kinds of things about it.


Actually I already did that, checking the contents of the variables to make sure everything was being retrieved correctly was one of my first thoughts, I have

Code: Select all
<?php
echo "Value 1: " . $value_1 . "<br>";
echo "Value 2: " . $value_2 . "<br>";
print_r($_SESSION);
echo "<p>Response: " . $value_2 . "</p>";
?>


At the top of the page I simply didn’t add that when I made the post originally. Now what I see when I first load up the page is something like

Value 1: 43
Value 2: 327
Array ( [total] => 370 )
Response:
What is 43 + 327 ?


After I hit the submit button I get something like

Value 1: 621
Value 2: 666
Array ( [total] => 1287 )
Response: 370
What is 621 + 666 ?
incorrect


Now as you can see when I hit the submit button the random values change thus changing the answer, and therefore no matter what answer I input it's always wrong.

As you can see the answer value is being over written each time the submit button is pressed so when I come to retrieve it to do the check the check fails because the value has changed so I need to figure out how to store the value correctly so it wont change when the submit button is pressed.

Now my next though was that maybe I just need to use a session so I recoded things to make it a little simpler at least until I figure out how to solve this glitch so what I have now is

Code: Select all
<?php

//Start Session
session_start();

//Generate Random Numbers
$value_1 = rand(1,1000);
$value_2 = rand(1,1000);

//Sum Of the Generated Numbers
$answer = $value_1 + $value_2;

//Display The Question
$question = "What is " . $value_1 . " + " . $value_2 . " ? ";

//Store The Answer To The Question
$_SESSION['total'] = $answer;

//Get The Users Response
$response = $_POST['response'];

//Check is Submit Has been pressed
if(isset($_POST['submit']))
{
  //If the stored answer is identical to the users response
  if($_SESSION['total'] === $response) {
  $message = "correct";
  }
  else {
  $message = "incorrect";
  }   
}
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>test</title>
</head>

<body>

<?php
echo "Value 1: " . $value_1 . "<br>";
echo "Value 2: " . $value_2 . "<br>";
print_r($_SESSION);
echo "<p>Response: " . $response . "</p>";
?>

<form action="random_math_question.php" method="post">
<p><?php echo $question; ?>
<br><input type="text" name="response"> <?php echo $message; ?></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>

</body>
</html>


Even though I striped this down to make it easier to track down what's causing the glitch I still have basically the same problem now granted this is all on one page but it shouldn’t really make any difference and in fact when I tried splitting it across 2 pages I still got the same issue so clearly I'm still missing something, so far the only way I have gotten this to work correctly is to use a hidden field but I though the idea of using a session was that it was supposed to eliminate the need to do that as the value is already stored on the server therefore meaning I simply need to grab the users input and then compare the two to see if they match.

Bethrezen
 
Posts: 375
Joined: September 13th, 2003, 11:56 am

Post Posted March 31st, 2017, 1:50 pm

ok so after some further investigation I think I sussed it out

my code in the previous example was basically right but what was happening is that every time I hit the submit button a page reload was triggered which changed the random values, which in turn updated the answer value which then invalidated the answer given by the user thus causing the check to fail even if the correct answer was given

what I needed to do was to change

Code: Select all
//Store The Answer To The Question
$_SESSION['total'] = $answer;


to

Code: Select all
//Update the answer value if
//1.) the submit button has not been pressed.
//2.) or the user got the question wrong.
//3.) or the user got the question right.

if(!isset($_POST['submit']) or $error === true or $sent === true)
{
  //Store The Answer To The Question
  $_SESSION['total'] = $answer;
}


so that the answer value will only be updated if submit has not been pressed if the user got the question wrong or the user got the question right.

I also discoverer var_dump(); which returns

Code: Select all
array(1) { ["total"]=> float(0.33) }
array(2) { ["response"]=> string(4) "1.05" ["submit"]=> string(6) "Submit" }


so it seems you where correct about the response variable containing string data instead of either an integer (whole number) or a float (decimal number)

which of course is going to cause trouble if you try to compare them with the strict comparison operator because even though the values might be the same because the data types are different it wont work because obviously a string/integer/float are not the same

so in order to fix that I needed to change

Code: Select all
if($_SESSION['total'] === $_POST['response']


to

Code: Select all
if($_SESSION['total'] === (real)$_POST['response']
or $_SESSION['total'] === (integer)$_POST['response'])


so now I just need to figure out the validation

Return to Web Development / Standards Evangelism


Who is online

Users browsing this forum: No registered users and 2 guests