micky micky - 7 months ago 6
SQL Question

Comparing only the selected value in loop to avoid error message

I am trying to build a basic quiz system.The following code shows how user choose the answer using radio butto and the getresult.php compares the radio input value with answer column. In my database there is a question, opt1, opt2, opt3, opt4, and answer columns.

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

while($myrow = $result->fetch_assoc())
{

echo $myrow['id'];
echo ".";
echo $myrow['question'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt1'].">";
echo $myrow['opt1'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt2'].">";
echo $myrow['opt2'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt3'].">";
echo $myrow['opt3'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' 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();

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

if($submit)
{
while($myrow = $result->fetch_assoc())
{

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

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


Everything is correct, but if I do not select a radio button from a question, i.e if I leave the question it displays undefined offset error which is obvious but how can I not display that. OR how can I compare only chosen options?

Answer

You should try array_key_exists() like this:

    if(array_key_exists($myrow['id'], $mycheck)
        && array_key_exists('answer', $myrow)
        && $mycheck[$myrow['id']]==$myrow['answer'])
    {   
        $count=$count+1;
    }

Or better yet, request your answers from database based on validated rows.