简体   繁体   中英

Codeigniter search with multiple fields

I've tried to make a search field with two parameters. One for name and the other one for location . But my code returns only the results for the first parameter. Maybe someone could figure out what's wrong. Below it's my code.

Mode:

public function search_job($keyword, $location){
    $query = $this->db->like('name', $keyword)
                ->like('location', $location)
                ->or_like('description', $keyword)
                ->get('jobs');

    return $query->result_array();
}

Controller:

public function search_job(){
    $location = $this->input->post('location');
    $keyword = $this->input->post('keyword');

    if ($this->input->post('submit')) {
        $this->Job_model->search_job($keyword, $location);
    }
}

I think your query is getting messed up when no $keyword is passed, try below query.

Code :

public function search_job($keyword, $location){
    $this->db->select('*');
    $this->db->from('jobs');
    if(!empty($keyword)) {
        $this->db->group_start();
        $this->db->like('name', $keyword);
        $this->db->or_like('description', $keyword);
        $this->db->group_end();
    }
    $this->db->like('location', $location);
    $query = $this->db->get();

    return $query->result_array();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM