doufan2541 2019-02-27 19:14
浏览 257

如何在php中检查数组循环中的多个单选按钮

I have fetched data and show in the radio buttons while the radio buttons are in loop, and insert the data in loop too.

The problem is that I can check only one radio button from the form, for each question one radio button must be check, which I can't.

layout

<form  method="POST" class="form-horizontal">
<?php 
$count=1;
$que="SELECT * FROM addques WHERE quz_id='$var'";
$dbd=mysqli_query($conn,$que);
    while ($cmd=mysqli_fetch_array($dbd)) {
            $quest=$cmd['qusname'];
            $ans_id=$cmd['ans_id'];
            $opt1=$cmd['qpta'];
            $opt2=$cmd['optb'];
            $opt3=$cmd['optc'];
            $opt4=$cmd['optd'];
            $answ=$cmd['answer'];?>
<b>Question &nbsp; <?php echo $count++;?>&nbsp;:<br><?php echo $quest;?></b><br><br>
<fieldset>
<input type="hidden" name="ansid[]" value="<?php echo $ans_id; ?>">
<input type="radio" name="ans[]" value="1"><?php echo $opt1;?><br><br>
<input type="radio" name="ans[]" value="2"><?php echo $opt2;?><br><br>
<input type="radio" name="ans[]" value="3"><?php echo $opt3;?><br><br>
<input type="radio" name="ans[]" value="4"><?php echo $opt4?><br><br><br>
</fieldset>
<?php } ?>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div> 
<?php
$i=0;
if (isset($_POST['submit'])) {
while ( $i<$noquestions  ) { 
$query="INSERT INTO `result`(  `quz_id`, `ans_id`, `answer`) VALUES('";
$query.=$var .  "', '"; 
$query.=$_POST['ansid'][$i] .  "', '"; 
$query.=$_POST['ans'][$i] .  "' )";
$db=mysqli_query($conn,$query);
$i++;
}
}
?>
  • 写回答

1条回答 默认 最新

  • dskld5423 2019-02-27 19:25
    关注

    The reason why you're getting that bug is you have given name="ans[]" so each time the index value incrementing.

    You can fix it by giving the following code

    <input type="radio" name="ans" value="1">
    <input type="radio" name="ans" value="2">
    

    And so on.

    You have been using radio button inside a loop so you can use it by setting a loop variable like name="ans[$i]"

    echo '<input type="radio" name="ans['.$i.']" value="1">
    <input type="radio" name="ans['.$i.']" value="2">';
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)