Ethan Guillotte Ethan Guillotte - 4 months ago 4
SQL Question

How to delete multiple entries using Checkboxes? (PHP)

So i've been looking at a few resources on using multiple checkboxes as input. I'm building a PM system and want the user to be able to check off any message and then delete them with a button.

The problem is that whenever I check off any message(s):

A: You have to click the delete button twice.

B: Only the first message ever in the list ever gets deleted.

The button group:

<form method="post"
<div class="button-group">
<button type="submit" name="delete" class="delete button inbox">Delete</button>
<button type="submit" name="mark" class="mark button inbox">Mark as Read</button>
</div>


Later on the table rows:

<?php
while ($row = mysqli_fetch_array($result)){?>
<tr>
<td><?php echo $row['PM_User1ID'];?></td>
<td><?php echo $row['PM_User2ID'];?></td>
<td><?php echo $row['PM_Subject'];?></td>
<td><?php echo $row['PM_Timestamp'];?></td>
<td>
<label>
<input type="checkbox" name="check_list[]" value="<?php echo $row['PMID'];?>"><?php echo $row['PMID'];?>
</label>
</form>
</td>
<?php echo '<td><a name="'.$row['PMID'].'"href = "?link='.$row['PMID'].'">Reply</a></td>'; ?>
</tr>
<?php } ?>


And finally the Submit Post:

<?php
if (isset ($_POST['delete'])){

if(!empty($_POST['check_list'])){

foreach($_POST['check_list'] as $selected){

$pmDelete = "DELETE FROM pm WHERE PMID = $selected";
$deletePM = $con->query($pmDelete);

}
}
}
?>


PM Page

GIF of issue

Answer

As it turns out (from conversing with the OP in comments), is that the empty() function for the checkboxes needed to be isset().

Then a (header) redirection was needed (upon successful deletion) in order to show the (new) results.

References:

You should also look into using a prepared statement:


Footnotes:

As I also mentioned, <form> cannot be child of <table> and the missing > for <form method="post" which would cause havoc.

Comments