使用准备好的语句删除带有PDO和复选框的多行

使用准备好的语句删除带有PDO和复选框的多行

本文介绍了使用准备好的语句删除带有PDO和复选框的多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码

$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>';

现在,除了一件事之外,一切都按预期工作,而且我还没有在互联网上找到任何答案.我的while循环将总是有多于一行,并且几乎总是希望从中删除多于一行.

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.

按照此脚本的形式,表单确实可以运行,但它只会删除最后一次单击的复选框.我知道为什么要这样做,但是我不理解如何克服这个问题.我正在使用PDO和准备好的语句.

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.

推荐答案

您正在为每个复选框分配相同的name="deletetask".因此,提交表单时,您只会收到最后选择的deletetask值.所以,你的错误在这里

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=

应该是

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

因此,您需要将deletetask重命名为deletetask[],以便您的复选框作为数组发送,而不是像这样

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

这篇关于使用准备好的语句删除带有PDO和复选框的多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:20