Jeann Pierre Jeann Pierre - 6 days ago 6
SQL Question

Code Igniter Search returns all records in table when input value is empty

Search results shows all the records when the keywords input is empty, how can I display a message that says search term not found?

What if I want to add another input value too, like input->post('date') ?

Controller:

$keywords = $this->input->post('keywords');

$data['results'] = $this->search_model->get_results($keywords );
$this->template->show('results',$data);


Model:

function get_results($keywords = 'default'){

$query = $this->db->select('*')->from('list')
->where("name LIKE '%$keywords%'")->get();

return $query->result_array();
}

Answer

Try using codeigniter $this->db->like method. If your $keyward is empty then try this...

$keywords = $this->input->post('keywords');
if(!empty($keywords)){
   $data['results'] = $this->search_model->get_results($keywords ); 
}else{
$data['result']="not found";
}
$this->template->show('results',$data);

Or

function get_results($keywords = null){

   if(!$keywords){
   return false;
   }
   $query = $this->db->select('*')->from('list')->like("name",$keywords)->get();
   return $query->result_array();
}

Every time your query run and return data because you pass $keyword='default' so if $keyword is empty then it search using default For more.....

Comments