我是PDO的新手,我已经对我面临的问题进行了一些搜索,但我无法找到任何答案。如下所示,我有这个功能:
function deleteInfo($id){
$pdo = connPDO();
$deleteInfo = $pdo -> prepare("DELETE FROM game_locais_zumbis WHERE id_zumbi IN (:id)");
$deleteInfo -> bindValue(":id", $id, PDO::PARAM_STR);
$deleteInfo -> execute();
$pdo = null;
}
之后,我有以下代码:
while($row = $listInfo -> fetch(PDO::FETCH_ASSOC)){
$ids[] = $row['ids'];
}
$ids = implode(',', $ids);
deleteInfo($ids);
当我回复我的$ ID时,我得到:
1,2,3,4,5
但DELETE函数并没有删除我的数据库中的所有这五行,而只删除了第一行,例如" 1"。当我在我的数据库中运行完全相同的DELETE函数时,替换":id"使用" 1,2,3,4,5",它确实有效!有人知道我的错误是什么吗?我感谢任何帮助。
答案 0 :(得分:3)
不幸的是,您无法使用预准备语句绑定元素数组。您必须直接在查询中构建它们。
function deleteInfo($ids)
{
$pdo = connPDO();
if (!is_array($ids))
$ids = array($ids); // if it is just one id not in an array, put it in an array so the rest of the code work for all cases
$ids = array_map([$pdo, 'quote'], $ids); // filter elements for SQL injection
$pdo->exec('DELETE FROM game_locais_zumbis WHERE id_zumbi IN (' . implode(', ', $ids) . ')');
}
请记住将数组传递给deleteInfo()
,而不是将其插入字符串中。
答案 1 :(得分:3)
我会这样做:
$query = "DELETE FROM game_locais_zumbis WHERE id_zumbi in (".str_repeat("?,", count($ids) - 1)."?)";
$stmt = $conn->prepare($query);
$stmt->execute($ids);
答案 2 :(得分:0)
我就是这样做的,而且效果很好。我创建了一个数组并循环遍历它。
<?php
// set a database connection
$host = "localhost";
$user ="root";
$password = "";
$db = "pdopost";
//Set a DSN
$dsn = 'mysql:host ='.$host . ';dbname='.$db;
// Create a PDO instance
$pdo = new PDO ($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$ids=['6', '7'];
foreach($ids as $id){
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
}
echo 'Deleted in the database';
?>