刷新页面后保持变量相同

时间:2015-09-24 18:59:08

标签: php

我正在创建一个数学修订版网站。在我无法将用户答案与正确答案进行比较时。当用户按下提交答案并且代码将用户答案与正确答案进行比较时,我怎样才能使变量$ correctanswer保持不变?

<?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>

1 个答案:

答案 0 :(得分:2)

您可以将其保存为以下会话:

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