2

For reasons that should be obvious, this is murder to search for...

How do I do this in PDO:

SELECT thing FROM things WHERE thing_uid IN ( ... )

My particular use case is a string built by exploding an array taken from a form with several dozen checkboxes. In standard MySQL this is very easy...

$thingString = implode("', '", $thingArray);
$q = "SELECT thing FROM things WHERE thing_uid IN ('$thingString')";

but I want that to benefit from PDO's anti-injection protection... bound params and all that. So how can I do it?

Drew
  • 6,208
  • 10
  • 45
  • 68

1 Answers1

6

Create an array of as many ? as you have values, and throw that into the query.

$placeholders = array_fill(0, count($thingArray), '?');
$sql = "SELECT thing FROM things WHERE thing_uid IN (" . implode(',', $placeholders) . ")";
Dan Grossman
  • 51,866
  • 10
  • 112
  • 101
  • 2
    Could also just use [`array_fill()`](http://php.net/manual/en/function.array-fill.php) – Phil Aug 15 '11 at 07:40
  • 2
    so I prepare that with the placeholder **?** equal in number to my params and then `$stmt->execute($thingArray);` and I'm good to go, correct? (can't test at the moment, so I'm asking) – Drew Aug 15 '11 at 07:40