4.4. Displaying Search Results

Writing a search engine in CodeIgniter, and especially for this project, is pretty straightforward. As you'll see, it's all about judiciously using the built-in wildcard-matching methods in your model to pull it off.

Without further ado, here's a search() function you can add to the MProducts model. You pass it a single argument, a search term, which is then used to match across the name, shortdesc, and longdesc fields of the products table. For now, this search function returns a maximum of 50 rows in the result set:

function search($term){
  $data = array();
  $this->db->select('id,name,shortdesc,thumbnail');
  $this->db->like('name',$term);
  $this->db->orlike('shortdesc',$term);
  $this->db->orlike('longdesc',$term);
  $this->db->orderby('name','asc');
$this->db->where('status','active');
  $this->db->limit(50);
  $Q = $this->db->get('products');
  if ($Q->num_rows() > 0){
    foreach ($Q->result_array() as $row){
      $data[] = $row;
    }
  }
  $Q->free_result();
  return $data;
}

Notice the use of $this->db->like() and $this->db->orlike()? These methods create wildcard matching on certain fields. The above code creates the following SQL statement:

select id, name, shortdesc, thumnail from products
where (name like '%$term%'
or shordesc like '%$term%'
or longdesc like '%$term%')
and status='active'
order by name asc
limit 50

Now that the search function is built, you can create the controller function called search(). Remember that this URL is loaded only when someone fills in ...

Get Professional CodeIgniter® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.