0

The below code will only work with one checkbox and ignores the rest. Is there any way that I can have it to delete selected checkboxes? I have tried using implode but it gives me

Warning: implode(): Invalid arguments passed

  <form action="" method="post">
 <input type="checkbox" name="id"  class="check" value = "<?php echo $row['id']; ?>">
 <?php echo $row['to_user'];?>
  <input type="submit" name="delete">
 </form>


    <?php

 if (isset($_POST['delete'])) {
 $id =  $_POST['id']; 
 $ids = implode( ',', $id );

 $mydb = new mysqli('localhost', 'root', '', 'database');
 $stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ?  and id = ? ");
 $stmt->bind_param('ss', $user, $ids);
 $stmt->execute();

echo "Message succesfully deleted";
exit();}

?>
5
  • What is then form code? Commented Aug 16, 2013 at 23:28
  • Where is the implode part? There is only one input Commented Aug 16, 2013 at 23:28
  • @EmilioGort I have included it now. Commented Aug 16, 2013 at 23:34
  • @barmar already answered your issue Commented Aug 16, 2013 at 23:37
  • Where is the loop that processes the query result? Are you really creating a separate form for each checkbox, instead of multiple checkboxes in one form? Commented Aug 16, 2013 at 23:40

1 Answer 1

3

Give the checkbox an array-style name:

<input type="checkbox" name="id[]"  class="check" value = "<?php echo $row['id']; ?>">

This will cause $_POST['id'] to be an array of all the checked values. Then delete them in a loop:

$mydb = new mysqli('localhost', 'root', '', 'database');
$stmt = $mydb->prepare("update messages set deleted = 'yes' where from_user = ? and id = ?");
$stmt->bind_param('ss', $user, $id);
foreach ($_POST['id'] as $id) {
    $stmt->execute();
}

You can't use a comma-separated list of IDs with =. You can use it with id in (...), but you can't do parameter substitution with this because the number of elements isn't known. So the loop is th best way to do it.

Sign up to request clarification or add additional context in comments.

8 Comments

array(1) { [0]=> string(1) "4" }
I don't believe you. That looks more like var_dump($_POST['id']).
oh yeah.. it is NULL
Sorry, that was a typo, I meant var_dump($_POST).
But if $_POST['id'] contains that array, it should be setting deleted = yes for ID 4. I assume you're setting $user correctly, that isn't anywhere in the question.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.