在MySQL"IN"中多次重复相同的数组用PDO查询 [英] Same array multiple times in MySQL "IN" query with PDO
问题描述
我需要使用PDO两次执行"IN"查询,该查询具有两次元素(数组)列表,以避免SQL注入. 我需要的查询是:
I need to execute an "IN" query which has a list of elements (array) twice using PDO in order to avoid SQL Injection. The query that I need is:
SELECT user_id
FROM user
WHERE google_id IN ('123123123abacaa','123bac21')
OR facebook_id IN ('123123123abacaa','123bac21');
如您所见,元素列表始终相同. 但是我不知道如何将数组分配给第二个"IN"语句,PHP向我抛出无效参数号"错误. 这是我的代码:
As you can see, the list of elements is always the same. But I don't know how to asign my array to the second "IN" statement, PHP throws me an "Invalid parameter number" error. Here is my code:
$list = implode(',', array_fill(0, count($ids), '?'));
$sql = "SELECT user_id
FROM user
WHERE google_id IN (".$list.")
OR facebook_id IN (".$list.");";
$stmt = $db->prepare($sql);
$stmt->execute(array_values($ids));
有人可以告诉我如何实现吗?
Could anyone tell me how to achieve this?
提前谢谢
所提供的可能重复"有点不同,因为我需要在SQL子句中两次使用数组
A bit different of the provided "possible duplicated" because I need to use the array two times in the SQL clause
解决方案:正如@u_mulder所说,通过更改以下代码的"execute"语句可以轻松解决该问题:
SOLUTION: As @u_mulder say it's easily solved by changing the "execute" statement for:
$stmt->execute(array_merge(array_values($ids), array_values($ids)));
推荐答案
在您的情况下,您可以将参数数组与其自身合并:
In your case you can just merge array of your params with itself:
$stmt->execute(array_merge(array_values($ids), array_values($ids)));
这篇关于在MySQL"IN"中多次重复相同的数组用PDO查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!