codeigniter db query子句不起作用

ejk8hzay  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(315)

我建立了一个查询:

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子句不起作用。它应该只返回用户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中尝试了此查询,但仍忽略了和用户\u id=3。如果我的逻辑没有错误,它应该只返回user\ id=3的行,但返回all。

insrf1ej

insrf1ej1#

试试这个

public function getContacts($limit, $start, $search)
{
  $this->db->select('*');
  $this->db->from('contact');
  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);
  }

  $this->db->where(array('user_id' => 3));
  $this->db->limit($limit, $start);
  $query = $this->db->get();
  return $query->result_array();
}
cbjzeqam

cbjzeqam2#

您需要添加group\u start()和group\u 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();
    }
uubf1zoe

uubf1zoe3#

请尝试以下代码:

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

}

相关问题