Home > Enterprise >  How can I use checkboxes to delete rows with php and mysql
How can I use checkboxes to delete rows with php and mysql

Time:01-05

I created a table with database information and tried to create checkboxes to be able to delete lines more easily, but something is not working correctly.

I have a button with form:

<form action="delete-register.php" method="post">
   <button type="button" ><span ></span>New</button>
   <button type="submit" name="delete" ><span ></span>Delete</button>
</form>

And I have rows with checkboxes:

<form action="delete-register.php" method="post">
  <td>
     <div >
       <input type="checkbox"  id="<?php echo $row['id']; ?>" name="selected[]" value="<?php echo $row['id']; ?>">
       <label  for="<?php echo $row['id']; ?>"></label>
     </div>
  </td>
</form>

And there is 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;
  }
}

The problem is that "selected" is always null and so nothing is deleted from the database. How can I solve this problem?

CodePudding user response:

Please note that the data submitted will be within the scope of <form>....</form>

Since you have two forms, when you click the submit button in the 1st form, it will not send the data of the 2nd form to the server.

Hence, please change the 2nd form to:

<form action="delete-register.php" method="post">

      <div >
       <input type="checkbox"  id="<?php echo $row['id']; ?>" name="selected[]" value="<?php echo $row['id']; ?>">
       <label  for="<?php echo $row['id']; ?>"></label>
     </div>

<input type=submit name=delete>

</form>

[Additional Remark]

If you want to stick to using the 1st form to trigger the delete action, then please:

  1. in the 1st form, change the delete from "submit" to "button"
  2. add an onclick event to this delete button so that it will trigger submission of the 2nd form
  3. make sure you have a hidden field known as "delete" in the 2nd form since you specified to have this field in your PHP script
  4. you may have noticed that I have added id=form2 in the 2nd form so as to facilitate triggering of the submission by form1

So this is the revised code:

<form method="post">
   <button type="button" ><span ></span>New</button>

   <button type="button" name="delete" 
onclick='document.getElementById("form2").submit()';
   ><span ></span>Delete</button>

</form>



<form id=form2 action="delete-register.php" method="post">

   <div >
       <input type="checkbox"  id="<?php echo $row['id']; ?>" name="selected[]" value="<?php echo $row['id']; ?>">
       <label  for="<?php echo $row['id']; ?>"></label>
     </div>

<input type=hidden name=delete value="delete">

</form>
  • Related