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

前端之家收集整理的这篇文章主要介绍了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;
    }

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

原文链接:https://www.f2er.com/php/136661.html

猜你在找的PHP相关文章