在CodeIgniter中查询多个where子句

时间:2015-04-11 16:04:08

标签: codeigniter where

我试图用severel where子句进行查询,但是它给出了错误的结果。我需要看到这些用户的role_id = 1(即学生),这些用户未被停用。我接受$this->uri->segment(3) = teacher_id。第三个条款是我只需要在同一所学校和老师学校一起学习的学生,我带$this->uri->segment(3)。我的疑问是:



public function select_students() {
   

      $this->db->select('*');
      $this->db->from('users');
      $this->db->where('deactivated_at = "0000-00-00 00:00:00" || deactivated_at IS NULL 
        AND role_id =1 AND school_id = ("SELECT school_id FROM users WHERE user_id=$this->uri->segment(3)")');
 $result=$this->db->get();
        return $result->result();
  }




我找到了解决方案:



 public function select_students() {
  
        $this->db->select('*');
        $this->db->from('users');
        $this->db->where('(users.deactivated_at = "0000-00-00 00:00:00" OR users.deactivated_at IS NULL) AND users.role_id = 1 ');
        $this->db->where('users.school_id',$this->uri->segment(4) );
        $result=$this->db->get();
            return $result->result();
 }




1 个答案:

答案 0 :(得分:2)

更好地使用自定义SQL,然后用CI方法包装。这将为您提供编写任何自定义查询的灵活性,以及​​使用CI安全性保护查询。

public function select_students() {
   $sql = SELECT * FROM users WHERE deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL AND role_id =1 AND school_id = (SELECT school_id FROM users WHERE user_id= (int) $this->uri->segment(3));
   $query = $this->db->query($sql);
   return $query->result();
 }