How to work with IN instruction in PHP + PDO?

Asked

Viewed 155 times

2

I’m trying to build a dynamic SQL but I’m getting beat up for not understanding how to work with the IN statement in PDO Example:

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

Field is Integer, I assumed that 1.2 would enter without problems as value, but it says that the search value is invalid, tried in several ways but without success

How to work with this instruction in PDO? As branch breaks I used the OR instruction, but let’s face it is not the best option! The Database is Postgres, but I think that’s not the case, because I could not in Mysql also

1 answer

2

From what I understand your code didn’t work, correct ?

Try using a name by 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");
$Query->Execute();

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

@EDIT

A solution would also be this:

<?php
$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);

$Query->execute();
?>
  • 1

    I prefer that answer because it prevents attacks from second order SQL injection, by not passing the array values directly to the query. Congratulations on the beautiful answer. + 1

  • I even thought of using explodes, but I thought it had a more elegant way of working the IN clause with PDO

  • 1

    It is @Marcelo, will have times that we have to work in a less elegant way because of these conflicts in certain things in PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.