How to work with the IN statement in PHP + PDO? [duplicate]


I'm trying to build a dynamic SQL but I'm getting caught by not understanding how to work with the IN statement in the PDO Example:

$SQL = "select * from tabela where (campo in(:valor))";
$Query = Database::Prepare($SQL);
$Query->bindValue(":valor", "1,2");

How to work with this statement in PDO? As a branch break I used the OR statement, but let's face it, it's not the best option! The Database is Postgres, but I think it is not the case, because I could not in MySQL either

asked by anonymous 18.08.2017 / 22:20

1 answer


I understand that your code did not work, right?

Try to use one name per value:

$SQL = "SELECT * FROM tabela WHERE campo IN (:valor1, :valor2, :valor3)";
$Query = Database::Prepare($SQL);
$Query->bindValue(":valor1", "1");
$Query->bindValue(":valor2", "2");
$Query->bindValue(":valor3", "3");

I believe the easiest and fastest way for you to do your code.


One solution would also be this:

$ids     = array(1, 2, 3, 7, 8, 9); //Valores de cada nome
$inQuery = implode(',', array_fill(0, count($ids), '?'));

$Query = Database::Prepare(
    'SELECT *
     FROM tabela
     WHERE campo IN (' . $inQuery . ')'

foreach ($ids as $k => $id)
    $Query->bindValue(($k+1), $id);

18.08.2017 / 22:25