【问题标题】:php Bind array to IN()php 将数组绑定到 IN()
【发布时间】:2016-05-31 19:10:52
【问题描述】:

我正在尝试将数组传递给SELECT * FROM table WHERE IN() 语句。我期待3个结果。但我得到了 2 个结果。

我在以下 2 个帖子中知道同样的问题

Can I bind an array to an IN() condition?

MySQL WHERE IN () + AND , PDO returns only one row

但是我仍在学习 php pdo,因此我对代码的理解不足以弄清楚如何将他们的代码重新用于我的代码。

希望有人能指出我哪里做错了。因为我从 select in 语句中得到了部分结果。我怀疑我没有正确地将数组传递到 IN() 中。

下面是我的控制页面的php代码

$customer_ids = array(1,2,3,4,5,6,7); 
//in actual case I get array from another query.

$customer_id = implode(',',$customer_ids);
//add comma to the array

$template->orders = $rephome->getOrder($customer_id);
//passing the imploded array into my Model page with class named rephome, 
//call on the method of getOrder, which is the select query

下面是我的模型页面。

public function getOrder($customer_id){
$this->db->query("SELECT * FROM orders WHERE customer_id_fk IN(.$customer_id.)");
$results = $this->db->resultset();
return $results;

以下是我的数据库类中的内容

public function query($query) {
        $this->stmt = $this->dbh->prepare($query);
    }


    public function bind($param, $value, $type = null) {
        if (is_null ( $type )) {
            switch (true) {
                case is_int ( $value ) :
                    $type = PDO::PARAM_INT;
                    break;
                case is_bool ( $value ) :
                    $type = PDO::PARAM_BOOL;
                    break;
                case is_null ( $value ) :
                    $type = PDO::PARAM_NULL;
                    break;
                default :
                    $type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue ( $param, $value, $type );
    }


    public function execute(){
        return $this->stmt->execute();
    }


    public function resultset(){
        $this->execute();
        return $this->stmt->fetchAll(PDO::FETCH_OBJ);
    }

【问题讨论】:

  • 使用与数组中的项目一样多的占位符构建 PDO 字符串。用适当的值绑定每个占位符。
  • 无论如何,“问题”是".. IN(.$customer_id.)" 导致.. IN(.1,2,3,4,5,6,7.) 这是无效的SQL - . 只是字符串中的文字。错误消息会说得这么多。
  • 我想你刚刚解决了我的问题。通过删除点。我得到了正确的结果。

标签: php mysql


【解决方案1】:

您没有绑定数组。您正在将数组转换为字符串,然后绑定该字符串。绑定参数只能表示单个值,而不是值列表,因此您的内爆/绑定版本在功能上与

SELECT ... foo IN ('1,2,3')

其执行与

完全相同
SELECT ... foo = '1,2,3'                   

而不是

SELECT ... IN (1,2,3)
               ^-^-^--- three separate values

使用单个占位符根本不可能实现您想要的。您需要动态构建查询(每个值一个占位符),然后将数组传递给查询调用,例如

$temp = array_fill(1, count($customer_ids), '?');
$in_arg = implode(',', $temp);
$sql = "SELECT ... IN ($in_arg)";
$stmt = $db->prepare(sql);
$res = $stmt->execute($customer_ids);

这会产生一个类似的查询字符串

SELECT ... IN (?,?,?,....)

为您要绑定的每个值添加一个占位符。

【讨论】:

    【解决方案2】:

    您可以将 switch 语句的底部修改为类似的内容,它将使用, 分隔符识别您是否有arrayimplode,然后流入您的默认类型PDO::PARAM_STR ... 现在就是这样。

    case is_array ( $value ) :
        $value = implode(',', $value);
    default :
        $type = PDO::PARAM_STR;
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 1970-01-01
      • 2010-10-29
      • 2010-10-11
      • 1970-01-01
      相关资源
      最近更新 更多