php – 仅比较循环中的选定值以避免错误消息
发布时间:2020-12-13 13:11:45 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试构建一个基本的测验系统.下面的代码显示了用户如何使用radio butto选择答案,getresult.php将无线电输入值与答案列进行比较.在我的数据库中有一个问题,opt1,opt2,opt3,opt4和答案列. form method="POST" action="getresult.php" labelEnter Your Na
我正在尝试构建一个基本的测验系统.下面的代码显示了用户如何使用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; } 或者更好的是,根据经过验证的行从数据库中请求您的答案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |