Search code examples
phparrayspdoprepared-statementwhere-in

PDO: Bind an array to an IN() condition with multiple WHERE clauses?


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

The above question doesn't have any answers for using multiple WHERE clauses.

The second best answer works only with one WHERE clause:

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

If I put an additional WHERE clause, it produces an empty result or error.

$qMarks = str_repeat('?,', count($ids) - 1) . '?';
$sth = $db->prepare("SELECT * FROM myTable WHERE id IN ($qMarks) AND locationid=?");
$sth->execute(array($ids, ?)); // Also tried $sth->execute($ids, $location_id) and $sth->execute($ids, array($location_id));

Please advise.


Solution

  • execute accepts a single array of parameters. You need to do:

    $sth->execute(array_merge($ids, [$location_id]));