php – 仅比较循环中的选定值以避免错误消息

我正在尝试构建一个基本的测验系统.下面的代码显示用户如何使用radio butto选择答案,getresult.PHP将无线电输入值与答案列进行比较.在我的数据库中有一个问题,opt1,opt2,opt3,opt4和答案列.
<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","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";
}

一切都是正确的,但是如果我没有从问题中选择一个单选按钮,即如果我留下问题它会显示未定义的偏移错误,这很明显,但我怎么能不显示.或者我如何只比较选择的选项?

你应该像这样试试 array_key_exists()
if(array_key_exists($myrow['id'],$mycheck)
        && array_key_exists('answer',$myrow)
        && $mycheck[$myrow['id']]==$myrow['answer'])
    {   
        $count=$count+1;
    }

或者更好的是,根据经过验证的行从数据库中请求您的答案.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...