我正在尝试构建一个基本的测验系统。以下代码显示了用户如何使用单选按钮toto选择答案,以及getresult.php将单选输入值与答案列进行比较。在我的数据库中,有一个问题opt1,opt2,opt3,opt4和Answer列。

<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";
}

一切都正确,但是如果我没有从问题中选择单选按钮,即如果我离开问题,它将显示未定义的偏移错误,这很明显,但是我怎么不能显示它。或如何比较仅选择的选项?

最佳答案

您应该像这样尝试array_key_exists():

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

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

关于php - 仅比较循环中选择的值,以避免出现错误消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36666335/

10-14 19:52
查看更多