你好,我有一个 PHP 代码,我在 while 循环中回显表单输入。我的代码的逻辑是,我从表中选择问题,然后在它获取行时,每次它都会回显一个用于多项选择题测验的表格。所以现在如果表中有 20 个问题,我的代码将回显 20 个带有问题的表单。现在,当我按下提交按钮时,我想从每个表单中获取每个选定单选按钮的值,并检查我表格的答案栏。 这是我的代码:
<?php
include 'connection.php';
$query = "SELECT question,type,option1,option2,option3,option4,option5,option6,answer FROM question WHERE exam_id = '$exam_id'";
$result = mysqli_query($connection, $query);
while($row=mysqli_fetch_assoc($result))
{
if ($row['type'] == "mcq") {
echo '
<form class="form-horizontal" role="form" method="POST" action="">
<div class="form-group">
<div class="col-sm-10">
<p>'. $row["question"] . ' </p>
</div>
</div>
<div id="form-label">
<p class="alignleft"><b>Answer:</b></p>
<div style="clear: both;"></div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-2">
A. <input type="radio" placeholder="" name="answer" value = "a" id="" required> ' . $row["option1"].
' </div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-2">
B. <input type="radio" placeholder="" name="answer" value= "b" id=""> ' . $row["option2"].
'</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-2">
C. <input type="radio" placeholder="" name="answer" value= "c" id=""> ' . $row["option3"].'
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-2">
D. <input type="radio" placeholder="" name="answer" value= "d" id=""> ' . $row["option4"].'
</form>';
}
?>
我的问题
我不知道将表单提交按钮放在哪里以获取 $_POST
值。如果我把它放在循环内,它会打印每个问题,或者如果我把它放在循环外,它就不会工作,因为届时表单标签已关闭。
我想做的是对于我想检查答案的每个问题,如果 $_POST['answer'] == $row['answer']
, $ _POST['answer']
是单选按钮的表单值
最佳答案
这是一种使用计数器的解决方案,只在打印完所有行后才在末尾添加提交标签
$count = 0;
while($row=mysqli_fetch_assoc($result))
{
$count = $count + 1;
if($count == Count($row)){
Add submit button here
}
}
关于PHP 在 while 循环中从输入表单中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45194014/