Php 刷新页面后保持变量不变
我正在创建一个数学复习网站。目前,我很难将用户的答案与正确答案进行比较。当用户按下submit answer并且代码将用户答案与正确答案进行比较时,如何使变量$correctanswer保持不变Php 刷新页面后保持变量不变,php,Php,我正在创建一个数学复习网站。目前,我很难将用户的答案与正确答案进行比较。当用户按下submit answer并且代码将用户答案与正确答案进行比较时,如何使变量$correctanswer保持不变 <?php require_once('connectvars.php'); if (isset($_POST['next'])) { // Grab the score data from the POST $answer = $_POST["answer"]; { // Co
<?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>
您可以将其保存为会话,如:
session_start();
// session is started if you don't write this line can't use $_Session
$_SESSION["correctAnswer"]=$correctAnswer;
这是一本手册,如果您以前从未使用过会话谢谢,它的工作原理与if i echo$_SESSION[“correctAnswer”]相同,但是:if($answer==$_SESSION[“correctAnswer”]){//Score counter echo'Correct!';}else{echo'Correct';}
上的输出总是不正确。对不起,我一直按enter键转到下一行,但它一直在发布我的评论。请尝试回显它们的会话和答案,以确保它们是相同的。另外,您还回显了正确的内容,看起来它已被注释掉