我有这段代码应该删除其复选框被选中的所有行(使用复选框进行多次删除)。
if (isset($_POST['del'])) {
$stmt = $db->prepare("DELETE FROM `$tbl_name` WHERE id=:id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$ids = array();
foreach ($_POST['del'] as $pval) {
$ids[] = (int)$pval;
$ids = implode(',',$ids);
$stmt->execute();
}
echo '<h1>Entries deleted.</h1>';
}
这是表单生成代码:
echo '<td><input type="checkbox" name="del[]" value="' . (int)$row['id'] . '"></td>';
如果选中单个复选框或单个删除,一切正常。 但是对于多个复选框,它会导致 fatal error :
Fatal error: [] operator not supported for strings in
我错过了什么吗?
最佳答案
此行导致 fatal error ,因为您用 implode()
的字符串结果覆盖数组 $ids
但在下一个循环迭代中尝试附加到再次使用 []
。
$ids = implode(',',$ids);
那应该被删除。您已经绑定(bind)了 $id
,因此您可以在 $id
的循环中执行 execute()
。
if (isset($_POST['del'])) {
// Prepare the statement before the loop
$stmt = $db->prepare("DELETE FROM `$tbl_name` WHERE id=:id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
// Execute the prepared statement in the loop with the ids from $_POST
// This is all you need, since $id is bound
foreach ($_POST['del'] as $id) {
$stmt->execute();
}
echo '<h1>Entries deleted.</h1>';
}
该方法使用循环。如果您将来自 $_POST['del']
的每个值与其自己的 ?
绑定(bind),您还可以执行带有位置参数的单个语句。这是更多的工作,而且可能只有当您要在每个循环中删除很多项时才值得这样做。
关于php - fatal error : [] operator not supported for strings multiple delete using PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20889152/