PHP 问题 : PDO Prepare() and Execute() with MYSQL IN() not working for arrays

标签 php mysql pdo execute prepare

我在 PHP 中使用 PDO 对象来运行 MYSQL 查询,我似乎在将 IN() 子句与 PDO::Prepare() 一起使用时遇到了问题。

用户输入:用逗号分隔的标签
例如)篮球,足球

我编写以下代码:

$query = 
"SELECT s.item_id, s.item_type, s.title
FROM search_all s 
WHERE EXISTS ( 
    SELECT t.item_id 
    FROM tags t 
    WHERE t.item_id = s.item_id AND t.item_type = s.item_type 
    AND t.tag IN (:tags) 
)";

$mysql_vars[':tags'] = implode("','",explode(',',$tags));
$stmt = $connection->prepare($query);
$stmt->execute($vars);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

据我了解,execute() 会将每个变量用双引号 (") 括起来,因此我在每个输入之间手动添加双引号,以模仿 sql,如下所示:

SELECT s.item_id, s.item_type, s.title
FROM search_all s 
WHERE EXISTS ( 
    SELECT t.item_id 
    FROM tags t 
    WHERE t.item_id = s.item_id AND t.item_type = s.item_type 
    AND t.tag IN ("basketball","football") 
)

但是,这对我不起作用。有没有办法在使用 sql IN() 子句的同时仍然使用 PDO 的 prepare() 和 execute() ?

最佳答案

你需要做一些像 AND t.tag IN (:tag1, :tag2)

现在它认为您正在文本中查找 "basketball","football"

为此,您可以使用 PHP 的字符串追加和循环来创建查询生成器 :)

关于PHP 问题 : PDO Prepare() and Execute() with MYSQL IN() not working for arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6444359/

相关文章:

java - 如何在 SQL 中动态创建 UPDATE 查询,其中每次调用的列都不同?

mysql - PDO更新语法困难

php - 使用 SQlite,如何显示当前的 PRAGMA 设置?

php - 如何从多维数组中删除空数组?

php - 从单元测试运行时,Laravel Schema::create 忽略表前缀

php - MySQL 查询代码对 Web 服务的两个不同字段使用 OR

php - 在函数之外传递变量 php

php - 错误: wrong mysql library version or lib not found (when building PHP 7 with a custom built MySQL 8)

Mysql:查找时间戳差异小于x的行

mysql - MariaDB 使用 PHP PDO 存储与原始字段值不同的 varbinary 字段