PHP PDO bindParam用于"IN"变量/字符串.陈述...? [英] PHP PDO bindParam for variable/string used for "IN" statement...?

查看:51
本文介绍了PHP PDO bindParam用于"IN"变量/字符串.陈述...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
PHP PDO:我可以将数组绑定到IN()条件?

Possible Duplicate:
PHP PDO: Can I bind an array to an IN() condition?

好的,这真的让我感到困扰.如何在PHP的PDO中为SQL"IN"语句绑定参数(具有多个值)?

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?

这是基础知识...

$allow = "'red', 'blue'";

SELECT * FROM colors WHERE type IN (:allow);

$stmt->bindParam(':allow', $allow);

当我自己插入$ 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?

注意:我确实将其余的PDO设置为与其他变量(而不是字符串)一起正常工作,我只是没有包含它,因为这是不必要的.

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.

基本上,您可以通过循环数组值并添加绑定名称来创建sql字符串的IN部分.

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
        )
    )
);

这将导致Select * from colors where type in ( :allow_0,:allow_1 )

然后循环$allow数组并使用bindValue绑定每个变量.

Then just loop the $allow array and use bindValue to bind each variable.

foreach( $allow as $k => $v ){
    $stmnt->bindValue( 'allow_'.$k, $v );
}


我在意识到与一个给出类似示例的问题相关的递减链接之前添加了此内容.我将其留在这里是因为它显示了如何使用命名的绑定变量而不是?s


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

这篇关于PHP PDO bindParam用于"IN"变量/字符串.陈述...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆