【问题标题】:where_in codeigniter error if array is empty如果数组为空,where_in codeigniter 错误
【发布时间】:2014-03-12 15:33:12
【问题描述】:

我正在使用 Codeigniter 2。我正在尝试使用 Active Record 进行 mysql 查询。问题是当传递给 where_in 的数组为空时出现错误。我在问如果数组为空,是否有任何方法可以忽略 where_in 条件

这是条件示例:

$this->db->where_in('p.brand_id', $brands);

这是我得到的错误:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在 ') AND p.brand_id IN () 附近使用的正确语法

【问题讨论】:

  • 别害怕,只要显示你的查询,伙计
  • @echo_Me:他$this->db->where_in('p.brand_id', $brands);WHERE IN 附加到查询中。这个问题很清楚。
  • 你确定 $brands 是一个数组吗?如果不是,它将失败...检查此link
  • @RocketHazmat 问题就在该行之前。这就是为什么我告诉他显示代码
  • @echo_Me 这是multiple join 的一个大查询所以,我告诉你我想要什么。 @Kurro1 我百分百确定。

标签: mysql activerecord codeigniter-2


【解决方案1】:

如果数组为空,请不要调用where_in()

if(is_array($brands) && count($brands) > 0){
    $this->db->where_in('p.brand_id', $brands);
}

【讨论】:

    【解决方案2】:

    我在 Active Record(DB_active_rec.php 类)中进行了更改,如果值数组为空,我将此代码添加到忽略 where_in 条件。所以它现在对我有用。 我添加的代码在 //@begin 和 //@end 之间

     /**
     * Where_in
     *
     * Called by where_in, where_in_or, where_not_in, where_not_in_or
     *
     * @param   string  The field to search
     * @param   array   The values searched on
     * @param   boolean If the statement would be IN or NOT IN
     * @param   string
     * @return  object
     */
    protected function _where_in($key = NULL, $values = NULL, $not = FALSE, $type = 'AND ')
    {
        if ($key === NULL OR $values === NULL)
        {
            return;
        }
    
        //@begin
        // Ignore where_in condition if values array's empty
        if(is_array($values) && empty($values))
        {
            return $this;
        }
                //@end
    
               // More method stuff
    

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 2020-03-26
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      • 1970-01-01
      相关资源
      最近更新 更多