开发者

Delete multiple rows with PDO and checkboxes using prepared statements?

开发者 https://www.devze.com 2023-04-01 13:27 出处:网络
I have this code, $q = $dbc -> prepare (\"SELECT * FROM tasks ORDER BY date_time LIMIT 0, 15\"); $q -> execute();

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开发者_StackOverflow社区.

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.


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


Here is a simple way to do multiple deletes from your database:

HTML

<input type="checkbox" name="del[]" value="your id">
<input type="checkbox" name="del[]" value="your id">
<input type="checkbox" name="del[]" value="your id">
<input type="checkbox" name="del[]" value="your id">

PHP

$ids = array();
foreach ($_POST['del'] as $pval) {
  $ids[] = (int)$pval;
}
$ids = implode(',',$ids);
$query = $db->prepare("DELETE FROM `pages` WHERE `pages_id` IN ( $ids )");
$query->execute();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号