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

社会主义新天地 提交于 2019-12-11 07:39:56

问题


I am using a PDO object in PHP to run MYSQL queries, and I seem to be having a problem with using the IN() clause with PDO::Prepare().

User Input: tags separated by a comma
ex) basketball,football

I code the following:

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

From what I understand, execute() will wrap each variable in double quotes ("), so I manually add double quotes between each input, to mimic the sql like:

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

This is not working for me, however. Is there any way to still use PDO's prepare() and execute() while using the sql IN() clause?


回答1:


You would need to do something like AND t.tag IN (:tag1, :tag2)

Right now it thinks that you are textually looking for "basketball","football"

To do this you can do a query generator using PHP's string appends and loops :)



来源:https://stackoverflow.com/questions/6444359/php-question-pdo-prepare-and-execute-with-mysql-in-not-working-for-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!