Same array multiple times in MySQL "IN" query with PDO

I need to execute an "IN" query that has a list of elements (array) twice using PDO to avoid SQL Injection. I need a query:

SELECT user_id 
FROM user 
WHERE google_id IN ('123123123abacaa','123bac21') 
   OR facebook_id IN ('123123123abacaa','123bac21');

      

As you can see, the list of items is always the same. But I don't know how to assign my array to the second "IN" query, PHP throws 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));

      

Can anyone tell me how to do this?

Thank you in advance

EDIT: slightly different from the "possible duplicate" provided because I need to use the array twice in the SQL statement

SOLUTION: As @u_mulder says it's easy to solve by changing the "execute" statement to:

$stmt->execute(array_merge(array_values($ids), array_values($ids)));

      

+2


source to share


1 answer


In your case, you can just merge your parameters array with yourself:



$stmt->execute(array_merge(array_values($ids), array_values($ids)));

      

+2


source







All Articles