如何使用计数器变量或任何其他替代方法为以下PHP代码中的每个单选按钮设置名称?
<?php
$id=0; //counter variable
$sql ="select roll_number,student_name,gender from student_table";
$query=mysqli_query($dbcon, $sql) or die(mysqli_error($dbcon));
while($post=mysqli_fetch_assoc($query)){
echo '<tr>';
echo '<td>'. $post['roll_number'] . '</td>';
echo '<td>'. $post['student_name'] . '</td>';
echo '<td>'. $post['gender'] . '</td>';
echo '<td width=250>';
echo '<input type="radio" name="rad'.$id'" value="P" />Present';
echo '<input type="radio" name="rad'.$id'" value="A" />Absent';
echo '<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>';
++$id;
echo '</td>';
echo '</tr>';
}
?>
答案 0 :(得分:0)
echo '<input type="radio" name="rad[' . $post['roll_number'] . ']" value="P" />Present';
echo '<input type="radio" name="rad[' . $post['roll_number'] . ']" value="A" />Absent';
在接收端你可能会这样:
$answers = $_POST['rad'];
foreach($answers as $roll_number=>$answer){
//do something with the $roll_number and $answer...
}
答案 1 :(得分:0)
更新了代码,将$post
更改为$row
,连接了字符串,修复了<button>
等等。在任何地方都没有表单声明 - 如果您只有一个表单,这将保存/获取表单中的每个项目 - 根据您的需要,您可能希望为每个学生声明一个表单,并使用唯一标识符。
<?php
$query = mysqli_query($dbcon, 'SELECT roll_number,student_name,gender FROM student_table') or die(mysqli_error($dbcon));
while ($row = mysqli_fetch_assoc($query)) {
echo '<tr>
<td>'.$row['roll_number'].'</td>
<td>'.$row['student_name'].'</td>
<td>'.$row['gender'].'</td>
<td width="250">
<label><input type="radio" name="rad['.$row['roll_number'].']" value="P">Present</label>
<label><input type="radio" name="rad['.$row['roll_number'].']" value="A">Absent</label>
<input type="submit" name="save" value="Save" class="btn btn-success btn-sm">
</td>
</tr>';
}
?>