PHP PDO bindParam for variable/string used for “IN” statement…? [duplicate]

試著忘記壹切 提交于 2019-12-30 13:31:07

问题


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.

Any help is appreciated, thank you.


回答1:


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




回答2:


The bind functions will treat the entire list as a string, not multiple discrete values.



来源:https://stackoverflow.com/questions/10808669/php-pdo-bindparam-for-variable-string-used-for-in-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!