Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple rows with PDO and checkboxes using prepared statements?

Tags:

php

mysql

pdo

I have this code,

$q = $dbc -> prepare ("SELECT * FROM tasks ORDER BY date_time LIMIT 0, 15");
$q -> execute();

echo '<form action="/adminpanel?tab=process" method="post">
          <input type="hidden" name="deletetask" />';

while ($todo = $q -> fetch(PDO::FETCH_ASSOC)) {

  echo '<div id="update"><div><strong>' 
           . $todo['date_time'] . '</strong><span>' . $todo['type'] 
           . '</span></div><p>' . $todo['message'] 
           . '</p><input class="checkbox" name="deletetask" value="' 
           . $todo['date_time'] . '" type="checkbox" /></div>';
}

echo '<input type="submit" value="Delete Tasks" /></form>';

Now everything works as expected apart from one thing and I haven't really found any answers on the internet. My while loop will have always more than one row, and will almost always want more than one deleting from it to.

As this script stands the form does work but it will only delete the last checkbox that was clicked. I understand why it is doing this, but I don't understand how to overcome this problem I am using PDO and prepared statements.

like image 901
carlgcoder Avatar asked Jun 04 '26 05:06

carlgcoder


1 Answers

You are assigning the same name="deletetask" for every checkbox. So, when you submit your form, you receive only last selected deletetask value. So, your mistake is here

<input class="checkbox" name="deletetask" value=

Should be

<input class="checkbox" name="deletetask[]" value=

So you need to rename deletetask to deletetask[] so your checkboxes is sent as an array and than do something like

$todelete = $_POST['deletetask']; 
//or $_GET, if you are submitting form through get. But I would recommend you using POST
$stmt = $pdo->prepare("DELETE FROM table WHERE id = ?");
foreach ($todelete as $id)
    $stmt->execute($id);
like image 124
J0HN Avatar answered Jun 06 '26 19:06

J0HN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!