有没有一种方法可以从数据库中返回用户在测试中未正确完成的问题和答案?

时间:2019-03-27 19:02:42

标签: php mysql

我正在写一个简短的php测验测验。对于未正确完成的问题,我希望代码能够返回问题编号和假定答案,对于正确的问题,我希望增加分数

到目前为止,编码工作正常,但是当我尝试将不正确的问题及其正确答案的数量添加到数组$ wrong_answer中时,我就堆栈了,无法解决

<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php 

      //Check to see if score is set_error_handler
    if (!isset($_SESSION['score'])){
       $_SESSION['score'] = 0;
    }


//Check if form was submitted
if($_POST){

    $number = $_POST['number'];
    $selected_choice = $_POST['choice'];
    $next=$number+1;
    $wrong_answer = array();
    $lesson = (int) $_GET['l']; 

    //Get total number of questions
    $query = "select * from questions where lesson_number = $lesson";
    $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 {
        foreach($number and $correct_choice){
            $wrong_answer [] = $number, $correct_choice;
        }
    }

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

1 个答案:

答案 0 :(得分:0)

当变量不是数组时,为什么要编写foreach循环? 你是想做

if($correct_choice == $selected_choice){
    $_SESSION['score']++;
}else {
     $wrong_answer=[$number,$correct_choice];
}

if($correct_choice == $selected_choice){
    $_SESSION['score']++;
}else {
     array_push($wrong_answer,[$number, $correct_choice]);//for 2d array
}