我有一个我想要内爆的数组,然后传递给查询并吐出所有匹配的值,但我得到的只是1064 violation
,我确定它错过了一些愚蠢的语法。
$filmImplode = implode("','", $filmList);
$query = "
SELECT
watch.film_id,
films.film_api_id
FROM
watch
INNER JOIN films ON films.film_id = watch.film_id
WHERE
films.film_api_id IN ('$filmImplode')
AND watch.user_id = :user_id";
$query_params = array(':user_id' => 1);
try {
$stmt = $db->prepare($query);
$getWatched = $stmt->execute($query_params);
} catch (PDOException $ex) {
echo 'something went wrong' . $ex->getMessage();
}
$getWatched = $stmt->fetchAll();
SQL错误读取
出了问题SQLSTATE [42000]:
语法错误或访问冲突:1064 SQL中有错误 句法;查看与MySQL服务器版本对应的手册 使用附近的正确语法 第3行的'item0','item1','item2','itme3','item4'
答案 0 :(得分:0)
我看到了两个潜在的问题:
: user_id
参数试试这个:
array_walk($filmList, function(&$film){
$film = $db->quote($film);
});
$filmImplode = implode(",", $filmList);
$query = "
SELECT
watch.film_id,
films.film_api_id
FROM
watch
INNER JOIN films ON films.film_id = watch.film_id
WHERE
films.film_api_id IN ($filmImplode)
AND watch.user_id = :user_id";
$query_params = array(':user_id' => 1);
try {
$stmt = $db->prepare($query);
$getWatched = $stmt->execute($query_params);
} catch (PDOException $ex) {
echo 'something went wrong' . $ex->getMessage();
}
$getWatched = $stmt->fetchAll();
根据建议here,更好的方法是动态构建编写占位符的IN
条件,然后在prepare
方法中绑定参数。
答案 1 :(得分:-2)
这个问题似乎是围绕着FilmImplode。 你的film_api_ids是int吗?如果没有,您应该确保它们在SQL中作为字符串常量传递。
WHERE films.film_api_id IN ('XXX-123-XX', 'YYY-456-YY')
而不是
WHERE films.film_api_id IN (XXX-123-XX, YYY-456-YY)
另外,那些单引号看起来很阴暗,如果所有的filmIds都是整数,请尝试不带单引号。
WHERE films.film_api_id IN ($filmImplode)