Adding Search to CodeIgniter Projects

This is a little tutorial that will add a Search function to your CodeIgniter projects. As you may already know, CodeIgniter is a PHP Framework that uses the MVC model. MVC stands for Model, Views and Controller. This article assumes you’ve work with CodeIgniter before and that you are looking for a search feature that you can add to your application. To add the search feature, we will get started with the Controller.

Controller

This is assuming you already loaded your libraries, helpers and database model. Lets add the Search function.

function search()
{
$data['query'] = $this->Books_model->get_search();
$this->load->view(‘books’, $data);
}

Model

In this database query, I am searching for any matches in any of the 4 fields: bookname, author, characters and synopsis. If there are matches, it will return the results.

function get_search() {
  $match = $this->input->post(‘search’);
  $this->db->like(‘bookname’,$match);
  $this->db->or_like(‘author’,$match);
  $this->db->or_like(‘characters’,$match);
  $this->db->or_like(‘synopsis’,$match);
  $query = $this->db->get(‘books’);
  return $query->result();
}

Views

Here’s the search form.

<?=form_open(‘books/search’);?>
<?php $search = array(‘name’=>’search’,'id’=>’search’,'value’=>,);?>
<?=form_input($search);?><input type=submit value=’Search’ /></p>
<?=form_close();?>

The result can be displayed using a HTML table.

<table>
<tr><th>ID</th><th>Book</th><th>Author</th><th>Published</th><th>Price</th></tr>
<?php foreach($query as $item):?>
<tr>
<td><?= $item->id ?></td>
<td><?= $item->bookname ?></td>
<td><?= $item->author ?></td>
<td><?= $item->datepublished ?></td>
<td><?= $item->price ?></td>
</tr>
<?php endforeach;?>
</table>

Let me know what you think.