mysql pdo in_PHP问题:MYSQL IN()的PDO Prepare()和Execute()无法用于数组

bd96500e110b49cbb3cd949968f18be7.png

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值