Hi everyone,
I have been using PDO to handle my database querying, and as part of this, I have made use of prepared statements. My problem is, i'm unsure how I would use the IN clause in a prepared statement?
Thanks.
| SitePoint Sponsor |
Hi everyone,
I have been using PDO to handle my database querying, and as part of this, I have made use of prepared statements. My problem is, i'm unsure how I would use the IN clause in a prepared statement?
Thanks.
As far as I know, you have to prepare arrays and loop for multiple IN(?,?,?....) and values!



Thanks for the responses, seems odd how the developers overlooked the IN clause when it comes to prepared statements.

Well, it is a pretty big can of worms. Also, in many cases a subquery will work better than having PHP handle the ids at all.
Id's can be kept in an array. To include the array
Code php:$sql = "SELECT * FROM table WHERE id IN ( ".implode(',',$array).")";
If you are paranoid about the values you can walk them first. For example, if they must be integers...
Code php:array_walk($array, function( &$value ) { $value = (int) $value });
If you need to quote wrap them.
Code php:array_walk($array, function( &$value ) { $value = PDO::quote($value) });
And yes, that's one of the rare instances where you'd need to use PDO::quote()
Great post @Michael Morris; I did not know how to do the last example so thanks.
Steve
Bookmarks