繁体   English   中英

如何使用复选框删除 php 和 mysql 的行

[英]How can I use checkboxes to delete rows with php and mysql

我创建了一个包含数据库信息的表,并尝试创建复选框以便能够更轻松地删除行,但有些东西无法正常工作。

我有一个带有表单的按钮:

<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”始终是 null,因此没有从数据库中删除任何内容。 我怎么解决这个问题?

请注意提交的数据将在<form>....</form>的scope内

由于你有两个forms,当你点击第一个表单的提交按钮时,它不会将第二个表单的数据发送到服务器。

因此,请将第二种形式更改为:

<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>

[补充说明]

如果你想坚持使用第一种形式来触发删除操作,那么请:

  1. 在第一种形式中,将删除从“提交”更改为“按钮”
  2. 向此删除按钮添加一个 onclick 事件,以便触发提交第二个表单
  3. 确保在第二种形式中有一个称为“删除”的隐藏字段,因为您指定在 PHP 脚本中包含此字段
  4. 你可能已经注意到我在2nd form中添加了id=form2以便于触发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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM