Home » Php » php – Comparing only the selected value in loop to avoid error message

php – Comparing only the selected value in loop to avoid error message

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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.

Answer:

When the form is submitted, the chosen values are passed as (for example):

mycheck[1]=2
mycheck[2]=3
mycheck[3]=1
mycheck[4]=2

…etc. Now if you leave one question unanswered, let’s say question 2, then no value will be submitted to the server for that question, so the submitted values could be something like this:

mycheck[1]=2
mycheck[3]=1
mycheck[4]=2

When PHP stores this in $_POST[], it will be an associative array:

$_POST['mycheck'] === array(
    '1' => 2,
    '3' => 1,
    '4' => 2
)

With extract($_POST) you get the following value for $mycheck:

$mycheck === array(
    '1' => 2,
    '3' => 1,
    '4' => 2
)

Now the following loop in your code will still go through all questions:

while($myrow = $result->fetch_assoc())
{
    if($mycheck[$myrow['id']]==$myrow['answer'])
    {   
        $count=$count+1;
    }
}

But (in the example) the check for question 2 will fail, because $myrow[‘id’] will equal 2, while $mycheck[2] does not exist. This produces the undefined offset error.

As an unanswered question obviously should not increase the count, you could solve this issue as follows: first test if the question was answered (does $mycheck have an entry for it?), and only if that is the case, retrieve the answer from that entry:

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

For the above extra test you can use array_key_exists, or isset.

Answer:

A bit rusted on PHP, but …
Have you tried using the isset() function? Or changing the error reporting level appropriately?

http://php.net/manual/pt_BR/function.error-reporting.php

Answer:

Why don’t you create a new radio button “Don’t know ” which would be initially checked

<input type="radio" name="" checked> 

So by default that button will be checked.