MYSQL - PDO with multiple IN clause

I can successfully implement an IN clause in a prepared PDO statement using the following code.

in_array = array(1,2,3);
$in  = str_repeat('?,', count($in_array) - 1) . '?';
$sql = "SELECT * FROM my_table WHERE my_value IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($in_array);
$data = $stm->fetchAll();

      

How can I do the same for multiple $ in? For example, I tried the following unsuccessfully:

in_array1 = array(1,2,3);
$in1  = str_repeat('?,', count($in_array) - 1) . '?';
in_array2 = array(4,5,1);
$in2  = str_repeat('?,', count($in_array) - 1) . '?';
$sql = "SELECT * FROM my_table WHERE (my_value1 IN ($in1)) AND (my_value2 IN ($in2))";
$stm = $db->prepare($sql);
$stm->execute($in_array1,$in_array2);
$data = $stm->fetchAll();

      

I think it has to do with stm-> execute but not sure helped to evaluate

+3


source to share


2 answers


Your current query is output as

SELECT * FROM my_table WHERE (my_value1 IN (?,?,?)) AND (my_value2 IN (?,?,?))

      

So your usage execute

is wrong, http://php.net/manual/en/pdostatement.execute.php . It should only pass one array with values โ€‹โ€‹inside it.

An array of values โ€‹โ€‹with as many elements as the SQL statement being executed has associated parameters. All values โ€‹โ€‹are processed as PDO :: PARAM_STR.

I think using array_merge, http://php.net/manual/en/function.array-merge.php will allow you to accomplish what you are trying



$stm->execute(array_merge($in_array1,$in_array2));

      

So doing is equivalent to

$stm->execute(array(1,2,3,4,5,1));

      

This might not seem correct as the folder pairs are now gone, but placeholder 1 (first question mark) will show up in 1

, placeholder 4 before 4

, etc.

+3


source


It doesn't make sense. Look at this:

$query = $db->prepare("SELECT * FROM table WHERE value1 = ? AND value2 = ?");
$query ->execute(array($value1, $value2));

      



and this:

http://php.net/manual/en/pdo.prepare.php

+1


source







All Articles