Possible Duplicate:
PHP PDO: Can I bind an array to an IN() condition?
Alright, this is really bothering me. How can I bind a paramater (which has multiple values) for an SQL "IN" statment in PHP's PDO?
Here are the basics...
$allow = "'red', 'blue'";
SELECT * FROM colors WHERE type IN (:allow);
$stmt->bindParam(':allow', $allow);
This works fine when I plug in $allow by itself, but when trying to bind it and use :allow it fails to work. Does anyone know why this is?
Note: I do have the rest of the PDO properly set with other variables (not strings) working, I just didn't include it because it's unnecessary.
What deceze said in the comments is correct. Here is a way i've done this before.
Basically you create the IN
part of the sql string by looping the array values and adding in a binded name.
$allow = array( 'red', 'blue' );
$sql = sprintf(
"Select * from colors where type in ( %s )",
implode(
',',
array_map(
function($v) {
static $x=0;
return ':allow_'.$x++;
},
$allow
)
)
);
This results in Select * from colors where type in ( :allow_0,:allow_1 )
Then just loop the $allow
array and use bindValue to bind each variable.
foreach( $allow as $k => $v ){
$stmnt->bindValue( 'allow_'.$k, $v );
}
I added this before realizing deceze linked to a question that gave a similar example. Ill leave this here because it shows how to do it with named binded variables and not ?s