我创建了一个包含数据库信息的表,并尝试创建复选框以便能够更轻松地删除行,但有些东西无法正常工作。
我有一个带有表单的按钮:
<form action="delete-register.php" method="post"> <button type="button" class="btn btn-primary"><span class="fe fe-file-plus fe-12 mr-2"></span>New</button> <button type="submit" name="delete" class="btn btn-secondary"><span class="fe fe-trash fe-12 mr-2"></span>Delete</button> </form>
我有带有复选框的行:
<form action="delete-register.php" method="post">
<td>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="<?php echo $row['id']; ?>" name="selected[]" value="<?php echo $row['id']; ?>">
<label class="custom-control-label" for="<?php echo $row['id']; ?>"></label>
</div>
</td>
</form>
还有delete-register.php:
if (isset($_POST['delete'])) {
if (isset($_POST['selected'])) {
foreach ($_POST['selected'] as $id) {
$query = "DELETE FROM registers WHERE id = $id";
mysqli_query($conn, $query);
}
header('Location: registers.php');
exit;
}
}
问题是“selected”始终为空,因此不会从数据库中删除任何内容。 我该如何解决这个问题?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Please note that the data submitted will be within the scope of
<form>....</form>由于您有两个表单,当您点击第一个表单中的提交按钮时,它不会将第二个表单的数据发送到服务器。
因此,请将第二种形式更改为:
<form action="delete-register.php" method="post"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="<?php echo $row['id']; ?>" name="selected[]" value="<?php echo $row['id']; ?>"> <label class="custom-control-label" for="<?php echo $row['id']; ?>"></label> </div> <input type=submit name=delete> </form>[补充说明]
如果您想坚持使用第一种形式来触发删除操作,那么请:
id=form2in the 2nd form so as to facilitate triggering of the submission by form1这是修改后的代码:
<form method="post"> <button type="button" class="btn btn-primary"><span class="fe fe-file-plus fe-12 mr-2"></span>New</button> <button type="button" name="delete" class="btn btn-secondary" onclick='document.getElementById("form2").submit()'; ><span class="fe fe-trash fe-12 mr-2"></span>Delete</button> </form> <form id=form2 action="delete-register.php" method="post"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="<?php echo $row['id']; ?>" name="selected[]" value="<?php echo $row['id']; ?>"> <label class="custom-control-label" for="<?php echo $row['id']; ?>"></label> </div> <input type=hidden name=delete value="delete"> </form>