如何从php测验应用程序中输出正确答案

时间:2019-10-11 01:17:39

标签: php html mysql forms session

我正在研究一个小的PHP测验项目,当学生寻求错误的答案时,我想给出正确的答案。 我该怎么办?

我想在最后一页上显示正确的答案。我已经在该页面上显示了最终成绩。

// Process code file
<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php 


    $selected_choice = $_POST['choice'];
    $next=$number+1;
    $total=4;

    //Get total number of questions
    $query="SELECT * FROM questions";
    $results = $mysqli->query($query) or die($mysqli->error.__LINE__);
    $total=$results->num_rows;

    //Get correct choice
    $q = "SELECT * FROM choices WHERE question_number = $number and is_correct=1";
    $result = $mysqli->query($q) or die($mysqli->error.__LINE__);
    $row = $result->fetch_assoc();
    $correct_choice=$row['id'];



    //compare answer with result
    if($correct_choice == $selected_choice){
        $_SESSION['score']++;
    } else {

    }


    if($number == $total){
        header("Location: final.php");
        exit();
    } else {
            header("Location: question.php?n=".$next."&score=".$_SESSION['score']);
    }}?> 

//这是最终的页面代码文件:

  <main>
<div class="container">
     <h2>You are Done!</h2>
     <p>Congrats! You have completed the test</p>
     <p>Final score: <?php echo $_SESSION['score']; ?></p>
     <a href="question.php?n=1" class="start">Take Test Again</a>
     <?php session_destroy(); ?>
</div>
  </main>


<footer>

</footer>

预先感谢。

1 个答案:

答案 0 :(得分:-1)

在检查的这一部分中,如果答案有误,请在会话中添加正确的答案 否则请从session

中删除正确答案
if($correct_choice == $selected_choice){
  $_SESSION['score']++;
  unset($_SESSION['correct_answer']);
} else {
  $_SESSION['correct_answer'] = $correct_choice;
}

之后,您可以像这样在page中轻松打印

<?php if(isset($_SESSION['correct_answer'])): ?>
<div class="alert alert-danger">
Correct Answer is: 
<?= $_SESSION['correct_answer'] ?>
</div>
<?php endif ?>
相关问题