Jamie
Jamie

Reputation: 13

Keeping a variable the same after refreshing the page

I am creating a Maths Revision website. At the minute i am having trouble at comparing the users answer with the correct answer. How can i have it so that the variable $correctanswer stays the same when the user presses submit answer and the code compares the users answer with the correct answer?

<?php
require_once('connectvars.php');
if (isset($_POST['next']))
{
// Grab the score data from the POST
 $answer = $_POST["answer"];
{
        // Connect to the database
        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        // Write the data to the database
        $query = "SELECT q_id, question, answer FROM a7680559_maths ORDER BY RAND() LIMIT 1";
$queryResult = mysqli_query($dbc, $query);
if ($queryResult->num_rows > 0) {
// output data of each row
if($row = $queryResult->fetch_assoc()) {
    echo"-Question: " . $row["question"]." - Answer: " . $row["answer"]."<br>";}}
$correctanswer = $row['answer']; 
echo $correctanswer;
        // Clear the score data to clear the form
    $answer ="" ;
        // Close the database connection
        mysqli_close($dbc); 
 }
}
elseif (isset($_POST['submit'])){
echo $correctanswer;
// Confirm the answer entered is the correct answer
        if ($answer == $correctanswer) 
        {
            // Score counter
            echo 'Correct!';
        }
        else
        {
            echo 'Incorrect';
        }
 }
else 
{
  echo '<p>Please press next question to continue.</p>';
  }
?>
  <hr />
 <form enctype="multipart/form-data" method="post" action="<?$_SERVER['PHP_SELF']; ?>">
<label for="answer">Answer:</label>
<input type="number" step="0.01" id="answer" name="answer" value="<?php if (!empty($answer)) echo $answer; ?>" />
<hr />
<input type="submit" value="Submit Answer" name="submit" /> <input type="submit" value="Next Question" name="next" />
 </form>

Upvotes: 1

Views: 76

Answers (1)

Cameron Spanos
Cameron Spanos

Reputation: 250

You could save it as a session like:

session_start();
// session is started if you don't write this line can't use $_Session      
$_SESSION["correctAnswer"]=$correctAnswer;

Upvotes: 2

Related Questions