【发布时间】:2021-04-06 11:58:43
【问题描述】:
有一个从 MySQL 数据生成的表,每一行都有一个包含多个表单的字段。
我需要在每行的第一个字段上放置一个复选框,包含唯一 ID,然后我需要通过 POST 使用位于表外的按钮传递多个复选框值。
当嵌套表单无法完成时,我如何获得它?
这是我的代码:
<!-- This button needs to be outside of the table -->
<button type="submit" form="selected_checkboxes">Send checked boxes</button>
<table>
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- If I put the form there, for the selected checkbox, it won't work, because the other forms
are nested inside the table -->
<form action="page.php" method="POST" name="selected_checkboxes"> <!-- THIS WON'T WORK -->
<?php
$db = $conn->prepare('SELECT * FROM accounts WHERE name = ? ORDER BY id DESC');
$db->bind_param('i', $name);
if (!$db->execute()) die('Error while fetching accounts: '. $conn->error);
$res = $db->get_result();
while ($data = $res->fetch_assoc()) {
$id = $data['id'];
$name = $data['name'];
echo '<tr>
<td><input type="checkbox" name="list[]" value="'.$id.'"></td>
<td>'.$name.'</td>
<td>
<form action="page.php" method="POST"><input type="hidden" name="id" value="'.$id.'" /><button type="submit" name="action1">Send</button></form>
<form action="page.php" method="POST"><input type="hidden" name="id" value="'.$id.'" /><button type="submit" name="action2">Archive</button></form>
</td>
</tr>
}
?>
</form> <!-- TO CLOSE THE NOT WORKING FORM -->
</tbody>
</table>
你会如何解决这个问题?
【问题讨论】:
-
在代码中使用
die(mysqli_error($$conn));是一个非常糟糕的主意,因为它可能会泄露敏感信息。更多解释见这篇文章:mysqli or die, does it have to die? -
@Dharman 我很感激,但这是一个个人项目,所以我不怎么看,但是谢谢
-
因为他们都去同一个地方,只需使用外部形式并测试各个动作($action1,$action2)
-
为什么?为什么您会忽略我的建议以使您的代码更简单更好?如果您只学习 PHP,那么请从学习最简单的解决方案开始。不要过于复杂。
-
@Dharman 不是让它更简单或更好,因为它是个人项目,甚至没有人会看到它
标签: php html forms post submit