mardi 22 mars 2016

Checkbox Quiz Multiple Choice

I am in the process of setting up a quiz which can have many answers for one question. The checkboxes are stored using an array and checked against my answers_bank table with the ab_name column (where the correct answers are stored).

All I am wanting to do is - if the answers which are checked are in the answers_bank table it echo's "correct", otherwise it echo's "incorrect" for the incorrect checked boxes.

The way I have tried to do it doesn't work, as it compares each individual answer in the array during each iteration and returns incorrect for the other answers (as it is not equal). This image should explain the issue I am having:

enter image description here

Here is a snippet of the code I have setup:

Returns the checkbox questions as shown in the first part of the image:

foreach ($qresults as $aresults) {
    $selected = $aresults["ab_name"];
    $ab_id = $aresults["ab_id"];
    ?>

    <input type="checkbox" name="checkbox[]"
           value="<?php echo $aresults["ab_name"]; ?>"> <?php echo $aresults["ab_name"]; ?> <br>

    <?php
}
?>

Aims to check if the answers are correct or not

foreach ($results as $row) {

$qb_id = $row['qb_id'];
$q_answer = $_POST["q$qb_id"];

$sql = "SELECT * FROM answers_bank WHERE ab_qb_id = :qb_id AND ab_correct = :correct";
$stmt = $db->prepare($sql);
$stmt->bindValue(':qb_id', $qb_id);
$stmt->bindValue(':correct', "correct");
$stmt->execute();
$qresults = $stmt->fetchAll();
foreach ($qresults as $cresults) {
    if (is_array($q_answer)) {
        foreach ($q_answer as $checkbox) {

            if ($checkbox == $cresults["ab_name"]) {
                echo "You said : " . $checkbox . " ... which is the correct answer!</br>";

            } else if ($checkbox != $cresults["ab_name"]) {
                echo "You said : " . $checkbox . " ... which is incorrect</br>";
            }

        }
    }
}

}

Any other solutions or corrections I can make to this? Thanks a lot!




Aucun commentaire:

Enregistrer un commentaire