I have written some code to make a search in the CodIgniter3 framework. When I insert 2 or more words to search input, it works great, however, when I enter just 1 word, it gives this error.
How can I solve this problem? Here is my controller:
function search() {
$keyword = strip_tags($this->input->get('searchforcourses'));
$keyword = explode(" ", $keyword);
$data['title'] = 'Bütün Kurslar Burada';
$data['courses'] = $this->courses_model->courses_search($keyword);
$this->load->view('templates/header');
$this->load->view('courses/courses', $data);
$this->load->view('templates/footer');
}
And here is my model:
function courses_search($keyword) {
$this->db->select('*');
$this->db->from('courses');
$this->db->like('title',$keyword[0]);
$this->db->or_like('title',$keyword[1]);
$this->db->join('instructors', 'instructors.id = courses.instructor_id', 'left');
$this->db->join('categories', 'categories.id = courses.category_id', 'left');
$query = $this->db->get();
return $query->result_array();
}
The error means you are trying to access an unexisting key 1
, your code is wrong on the model level, your code is only getting two keywords, what if the user searched for three keywords? are you just going to ignore them?
I suggest doing it like this:
function courses_search($keyword) {
$this->db->select('*');
$this->db->from('courses');
// You should consider limiting the number of keywords to avoid long loops
// Limits to 20 keywords
$keyword = array_slice($keyword, 0, 19);
// You can also limit it in the 3rd parameter of the explode function
// Loop through the keywords
forearch($keyword as $key){
$this->db->or_like('title',$key);
}
$this->db->join('instructors', 'instructors.id = courses.instructor_id', 'left');
$this->db->join('categories', 'categories.id = courses.category_id', 'left');
$query = $this->db->get();
return $query->result_array();
}