Codeigniter db query子句不起作用

时间:2018-04-10 04:20:29

标签: php mysql codeigniter

我构建了一个查询:

 public function getContacts($limit, $start, $search)
{

    $this->db->limit($limit, $start);

    if (!empty($search)) {
        $this->db->like('name', $search);
        $this->db->or_like('last_name', $search);
        $this->db->or_like('phone_number', $search);
        $this->db->or_like('created_at', $search);
        $this->db->or_like('note', $search);
    }



    $query = $this->db->get_where('contact', array('user_id' => 3));

    return $query->result_array();

}

但是where子句不起作用。它应该仅返回user_id等于3的结果,但它返回所有内容。

有什么问题?

这是执行的查询:

SELECT * FROM `contact` WHERE name LIKE '%stefano%' ESCAPE '!' OR last_name LIKE '%stefano%' ESCAPE '!' OR phone_number LIKE '%stefano%' ESCAPE '!' OR created_at LIKE '%stefano%' ESCAPE '!' OR note LIKE '%stefano%' ESCAPE '!' AND `user_id` = 3 LIMIT 2

在Workbench中尝试此查询并仍然忽略AND user_id = 3。 如果我的逻辑没有错,它应该只返回user_id = 3但返回all的行。

3 个答案:

答案 0 :(得分:3)

你需要添加group_start()和group_end()。就像这样。

 if (!empty($search)) {
      $this->db->group_start();
        $this->db->like('name', $search);
        $this->db->or_like('last_name', $search);
        $this->db->or_like('phone_number', $search);
        $this->db->or_like('created_at', $search);
        $this->db->or_like('note', $search);
        ->group_end();
    }

答案 1 :(得分:0)

试试这个

public function rules()
{
    return [
        'name' => 'required|max:255|unique:products,name'.$product->id,
        'description' => 'required',
        'price' => 'required|numeric|max:500',
        'stock' => 'required|max:6',
        'discount' => 'required:max:2'
    ];
}

答案 2 :(得分:-2)

试用此代码:

public function getContacts($limit, $start, $search)
{

    $this->db->limit($limit, $start);

    if (!empty($search)) {
        $this->db->select(*);
        $this->db->like('name', $search);
        $this->db->or_like('last_name', $search);
        $this->db->or_like('phone_number', $search);
        $this->db->or_like('created_at', $search);
        $this->db->or_like('note', $search);
    }



    $this->db->select(*);
    $this->db->where('user_id','3');
    $query = $this->db->get('tablename');
    return $query->result_array();

}