存储在会话中的分数显示错误的值

时间:2018-06-18 07:21:07

标签: javascript php html sql

我创建了一个带测验的网站,其中一次一个地从数据库加载问题。在所有问题结束时,将显示分数。

然而,在我添加“上一页”按钮后,分数显示错误。如果用户选择了一个选项并尝试编辑上一个问题,则还会添加上一个问题的计数。

我该如何解决?

以下是获取正确答案的代码:

<style>
.green{
  background-color:;
  margin:2px;
  padding:2px;
  color:black;
}
.red{
  background-color:;
  margin:2px;
  padding:2px;
  color:black;
}
</style>

<?php
// Start the session
session_start();

$con=mysqli_connect("localhost","root","","quiz"); // change here to your data
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// check correct unswer
if($_POST['next_id'] >= 0){
$correct_unswer=mysqli_query($con,"select answer from moh WHERE id =(select min(id) from moh where id > {$_POST['next_id']})");
$result=mysqli_fetch_array($correct_unswer,MYSQLI_ASSOC);
$correct_answer = $result["answer"];

//get user answer
$user_answer = 1;
if($_POST['answer2'] != 'false') $user_answer = 2;
if($_POST['answer3'] != 'false') $user_answer = 3;
if($_POST['answer4'] != 'false') $user_answer = 4;

// Save results in session


$_SESSION["last_answer"] = $user_answer;

if($correct_answer == $user_answer){
    $_SESSION["correct_score"] += 1;
} else{
    $_SESSION["not_correct_score"] += 1;
}





// query next question
$response=mysqli_query($con,"select * from moh WHERE id =(select min(id) from questions where id > {$_POST['next_id']})");
?>

<?php while($result=mysqli_fetch_array($response,MYSQLI_ASSOC)){ ?>

<div id="question_<?= $result['id'] ?>" data-id="<?= $result['id'] ?>" class='question'> <!--check the class for plurals if error occurs-->
  <h2><?= $result['id'].".".$result['question_name'] ?></h2>
  <div class='align'>
    <?php $answer_class = ($correct_answer == 1)? 'green' : 'red' ; ?>
    <div class="<?=$answer_class?>"><?= $result['answer1'] ?></div>
    <?php $answer_class = ($correct_answer == 2)? 'green' : 'red' ; ?>
    <div class="<?=$answer_class?>"><?= $result['answer2'] ?></div>
    <?php $answer_class = ($correct_answer == 3)? 'green' : 'red' ; ?>
    <div class="<?=$answer_class?>"><?= $result['answer3'] ?></div>
    <?php $answer_class = ($correct_answer == 4)? 'green' : 'red' ; ?>
    <div class="<?=$answer_class?>"><?= $result['answer4'] ?></div>
  </div>
</div>
<?php }?>
<?php mysqli_close($con); }?>

1 个答案:

答案 0 :(得分:0)

您应该在代码顶部放置session_start();,在任何HTML或文本之前

http://php.net/manual/en/function.session-start.php