cheunology
cheunology

Reputation: 41

How to check if radio button contains correct answers?

I have 2 tables in my database, 1 for questionnaires and 1 for correct answers. both have id linked to each other. code for displaying questions

while($row = $result->fetch_assoc()) {
        echo "<br><label>". $row["Question"] ."</label><br><br>";
        echo "<input type='radio' name='ans' value='ans1'>". $row["AnswerA"] ."</label><br>";
        echo "<input type='radio' name='ans' value='ans2'>". $row["AnswerB"] ."</label><br>";
        echo "<input type='radio' name='ans' value='ans3'>". $row["AnswerC"] ."</label><br>";
    }

and then when user hits submit, the it should check if the radio button which contains the correct answer. code for checking answers

  while($row = $result->fetch_assoc()) {
        if(isset($_POST['submit'])){
            if($_POST['ans']== $row["CorrectAns"]) {echo "Correct";}
            else {echo "Incorrect";}
        }
    }

I think this will work for only one question. However I have about 20 questions and 3 radio buttons each. What addition should i add while checking the answer? I am trying to avoid javascript in this one but if there is a simple js solution I am open for it

Upvotes: 0

Views: 83

Answers (1)

Akash Sharma
Akash Sharma

Reputation: 757

First, reduce the database round trips and reduce rows fetched from database.

If you have multiple questions, get all the correct answers from database for these questions. Then create one array with correct answers $answers[question_id] = $answer;.

Then check for all the answers submitted by the user with actual answers.

<?php

if(isset($_POST['submit'])){
    // $_POST['ans'] is array for all questions

    $submittedAnswers = [];
    $correctAnswers = [];

    foreach ($_POST['ans'] as $questionID => $answer) {
        $submittedAnswers[$questionID] = $answer;
    }

    // use mysql binding for actual query in production
    //$sql = "select * from answers where Question_ID in {" . implode(',', array_keys($submittedAnswers)) . "}";

    while($row = $result->fetch_assoc()) {
        $correctAnswers[$row["Question_ID"]] = $row["CorrectAns"];
    }

    $failedQuestions = [];


    foreach ($submittedAnswers as $questionID => $answer) {
        if ($answer != $correctAnswers[$questionID]) {
            $failedQuestions[] = $questionID;
        }
    }

}

Upvotes: 1

Related Questions