为什么PDO准备的SELECT语句中的多个WHERE条件导致查询中断

时间:2018-07-08 20:47:50

标签: php mysql pdo

执行此查询后,我会得到期望的响应(通过AJAX)。可以。

$stmt = $pdo->prepare("SELECT item_location AS Location,  users_description AS Description, price AS Price  FROM sale_items WHERE item_type IN ($cs_vals)”);

但是当我像这样向WHERE子句中添加另一个表列名称时:

$stmt = $pdo->prepare("SELECT item_location AS Location,  users_description AS Description, price AS Price  FROM sale_items WHERE (item_type, map_region) IN ($cs_vals)”);

...。我在控制台中收到“ JSON.parse:意外字符....”消息,但网页上没有任何显示。为什么是这样?我在这里做错了。在此先感谢您的帮助。 顺便说一句,$ cs_vals是格式('a','b','c'...)的逗号分隔值列表。此逗号分隔列表是由

生成的
$cs_vals = str_repeat('?,', count($arr) - 1) '?';

$ arr变量是从用户生成的表单中提取的非NULL值的数组。

2 个答案:

答案 0 :(得分:0)

我假设您了解FROM

您必须一次检查一个:

WHERE ((item_type) IN ($cs_vals) 
OR (map_region) IN ($cs_vals))

除非您尝试在数组中找到该组合。

答案 1 :(得分:0)

您使用EXISTS,而不是$cs_vals,而是使用UNION创建一个内联表,以便验证元组是否与您的列表匹配。

SQL DEMO

SELECT item_location AS Location,  users_description AS Description, price AS Price  
FROM sale_items 
WHERE EXISTS (SELECT 1
              FROM (SELECT 'A' as item_type, 1 as map_region
                    UNION 
                    SELECT 'B' as item_type, 2 as map_region
                    ) as T
              WHERE sale_items.item_type = T.item_type
                AND sale_items.map_region = T.map_region
              )

您也可以使用IN,但需要与元组进行比较:

SELECT item_location AS Location,  users_description AS Description, price AS Price  
FROM sale_items 
WHERE  (item_type, map_region) IN (('A',1),('B',2));