简体   繁体   中英

How should I make quiz with one answer for each question in php?

I'm trying to make a plain php quiz app. I'm trying to show all questions with different answers. The problem is, when I click on 1st questions answer radio button gets checked, but when I select 2nd questions answer, it's radio button gets checked but the one from 1st questions dissappears. I want to make a form that lets user select one answer from each question and then passes the data to test_calc.php file for processing. Here's the code:

<?php
    $connection = mysqli_connect("localhost", "root", "", "vartvald");
    if (isset($_GET['id'])) {
        $fk = mysqli_real_escape_string($connection, $_GET['id']);
    if ($connection->connect_error) {
        die("Connection failed:" . $connection->connect_error);
    } else {
        $sql = "SELECT * FROM questions WHERE fk_test='$fk'";
    }


    $result = $connection->query($sql);

    if ($result->num_rows > 0) {
        while ($row = mysqli_fetch_assoc($result)) {
            $id = $row['id'];
            $question = $row['question'];
            $mark = $row['mark'];
            $answer_1 = $row['answer_1'];
            $answer_2 = $row['answer_2'];
            $answer_3 = $row['answer_3'];
            $answer_4 = $row['answer_4'];
            $correct = $row['correct'];
            echo "<div><form method='POST' action='test_calc.php?id=".$fk."'><br><b>" . $row['question'] . "</b><br><input type='radio' name='answer[]' value=".$answer_1.">"
                    . $row['answer_1'] . "<br><input type='radio' name='answer[]' value=".$answer_2.">" . $row['answer_2'] . "<br><input type='radio' name='answer[]' value=".$answer_3.">" . $row['answer_3'] . 
                    "<br><input type='radio' name='answer[]' value=".$answer_4.">" . $row['answer_4'] . "<input type='hidden' name='mark' value=".$row['mark'].">
                    <input type='hidden' name='correct[]' value=".$row['correct'].">
                    <input type='hidden' name='id' value=".$row['id']."><br><br></div>";
        }
        echo '<button type="submit"><b>Baigti testa</b></button>';
    } else {
        echo "</table><h2 style='text-align:center'>Testas neturi sukurtu klausimu..</h2>";
    }
}

All radio buttons are in the same group: answer[]

You need a separate name for each question, for example like this:

echo "... <input type='radio' name='answer_".$id."[]' value=".$answer_4."> ..."

Set unique name for each questions in loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM