vendredi 15 avril 2016

basic multiple answers quiz system checkbox ambiguity

I am trying to build a basic quiz system and everything seems ok.

The following code shows how a users choose the correct answer and the getresult.php shows the result. In my database, there is a question, opt1, opt2, opt3 opt4 and answer column.

<form method="POST" action="getresult.php">
   <label>Enter Your Name:</label><br>
    <input type="text"  name="name" required><br><br>
<?php
    $db = new mysqli("localhost", "root", "","learndb");
    $stmt=$db->prepare("SELECT * FROM quiz");
    $stmt->execute();
    $result=$stmt->get_result();

        while($myrow = $result->fetch_assoc())
    {
        echo "<form method='POST' action='getresult.php'>";
    echo $myrow['id'];
    echo ".";   
    echo $myrow['question'];
    echo "<br>";
    echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt1'].">";
        echo $myrow['opt1'];
    echo "<br>";
    echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt2'].">";
    echo $myrow['opt2'];
        echo "<br>";
    echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt3'].">";
    echo $myrow['opt3'];
        echo "<br>";
    echo "<input type='checkbox' name='mycheck[]' value=".$myrow['opt4'].">";
    echo $myrow['opt4'];
        echo "<br><br>";

    }
?>
<input type="submit" name="submit" value="Get Results" class="btn btn-primary">

getresult.php

<?php
extract($_POST);
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
$myrow = $result->fetch_assoc();

$totalCheckboxChecked = sizeof($_POST['mycheck']);

$submit=isset($_POST['submit']);

$count=0;

if($submit)
{
    for($i=0;$i<$totalCheckboxChecked;$i++)
   {

               if($mycheck[$i]==$myrow['answer'])
        {   
            $count=$count+1;
        }

   }
    echo "Hello ";
    echo $_POST['name'];
    echo "<br>";
    echo "You scored ";
    echo $count;

}

Now the problem is with the checkbox, I can check all the values from all the questions. And when I use radio button I can check only one value from all questions. How can I check only one value from one question.




Aucun commentaire:

Enregistrer un commentaire