Can I bind an array to an IN() condition? Can I bind an array to an IN() condition? php php

Can I bind an array to an IN() condition?


You'll have to construct the query-string.

<?php$ids     = array(1, 2, 3, 7, 8, 9);$inQuery = implode(',', array_fill(0, count($ids), '?'));$db = new PDO(...);$stmt = $db->prepare(    'SELECT *     FROM table     WHERE id IN(' . $inQuery . ')');// bindvalue is 1-indexed, so $k+1foreach ($ids as $k => $id)    $stmt->bindValue(($k+1), $id);$stmt->execute();?>

Both chris (comments) and somebodyisintrouble suggested that the foreach-loop ...

(...)// bindvalue is 1-indexed, so $k+1foreach ($ids as $k => $id)    $stmt->bindValue(($k+1), $id);$stmt->execute();

... might be redundant, so the foreach loop and the $stmt->execute could be replaced by just ...

<?php   (...)  $stmt->execute($ids);


For something quick:

//$db = new PDO(...);//$ids = array(...);$qMarks = str_repeat('?,', count($ids) - 1) . '?';$sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks)");$sth->execute($ids);


Is it so important to use IN statement? Try to use FIND_IN_SET op.

For example, there is a query in PDO like that

SELECT * FROM table WHERE FIND_IN_SET(id, :array)

Then you only need to bind an array of values, imploded with comma, like this one

$ids_string = implode(',', $array_of_smth); // WITHOUT WHITESPACES BEFORE AND AFTER THE COMMA$stmt->bindParam('array', $ids_string);

and it's done.

UPD: As some people pointed out in comments to this answer, there are some issues which should be stated explciitly.

  1. FIND_IN_SET doesn't use index in a table, and it is still not implemented yet - see this record in the MYSQL bug tracker. Thanks to @BillKarwin for the notice.
  2. You can't use a string with comma inside as a value of the array for search. It is impossible to parse such string in the right way after implode since you use comma symbol as a separator. Thanks to @VaL for the note.

In fine, if you are not heavily dependent on indexes and do not use strings with comma for search, my solution will be much easier, simpler, and faster than solutions listed above.