phpsqlmysqlcodeigniterlogical-grouping

How to make a CodeIgniter active record query with like(), or_like(), and where() method calls?


This is a search function I made, it gets the search term and displays fine. HM_Jobs has 3 options for JobStatus: Open, Accepted or Complete.

However the search is also pulling results from the Accepted and Complete rows when I run it, why isn't the WHERE statement stopping this from happening?

function search_jobs($search) //This function checks a search term against the job title and description.
{
    $this->db->select('*');
    $this->db->from('HM_Jobs');
    $this->db->like('JobTitle',$search);
    $this->db->or_like('JobDescription',$search);
    $this->db->where('JobStatus','Open');  

    $query = $this->db->get();
    return $query->result(); 
}

Solution

  • Try this

     $this->db->select('*');
     $this->db->from('HM_Jobs');
     $this->db->where("(JobTitle LIKE '$search' OR JobDescription LIKE '$search')"  );
     $this->db->where('JobStatus','Open'); 
     $query = $this->db->get();
    

    You can see your query executed by using echo $this->db->last_query()

    Your query creates like

    where JobTitle like 'search' or JobDescription  like 'search' and JobStatus='Open'
    

    But the query you need require something like

      where (JobTitle like 'search' or JobDescription  like 'search') and JobStatus='Open'