php - 我需要帮助来解决嵌套的 FORM 问题
问题描述
有一个从 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>
你将如何解决这个问题?
解决方案
<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>
在本节中,我将使用热链接而不是表单对其进行修改,并制作不同的处理页面,例如:
echo "<td><a href='page2.php?action=send&id=".$id."'>Send</a> ";
echo "<a href='page2.php?action=archive&id=".$id."'>Send</a></td>";
并且 page2.php 将在 $_GET["action"] 和 $_GET["id"] 上运行,就像替换的迷你表单一样。
那么您从一开始的表单(带有复选框,您声明不起作用)将是唯一的表单并且可以工作:) 只有当您授予经过验证的用户访问权限时才可以。
希望这会推动你前进。
:)