Search data using CodeIgniter

This is another small tutorial based on CodeIgniter and Bootstrap done by me to give an idea of how to search records stored in database using CI. When we want retrieve a record filtered by a keyword, we have to use search function. Otherwise we have to search for all records to get the needed one. So, here I will explain how to implement a function to retrieve data of a user using a simple search button.

Since you are now familiar with my previous articles, I will cut some parts from this tutorial such as db configuration, CRUD operations and will just explain the core. If you are new to CI, refer to my previous articles and read this. It will be comfortable for you. As usual we have to do the basic CI configuration first. Now you are aware of them. If not;

Project folder => CISearch
Base URL => $config['base_url'] = 'http://localhost/CISearch/
Database name => pagination (I will use a previous database used by me. You can create a db with a suitable name)
Database table name => users
Autoload libraries => database
Autoload helpers => form , url
Default Controller => Search

Note : I have removed the index.php which you find when loading URLs. The way to remove it , is included in this article. If you have not removed it, add this part everywhere you call for controller functions. => /index.php

CREATE TABLE `users` (
  `indexno` int(10) NOT NULL,
  `username` varchar(30) NOT NULL,
  `email` varchar(30) NOT NULL
) ;

  ADD PRIMARY KEY (`indexno`);

Insert these data by selecting the database from phpmyadmin.

INSERT INTO `users` (`indexno`, `username`, `email`) VALUES
(1, 'salitha', ''),
(2, 'techpool', ''),
(3, 'lasitha', ''),
(4, 'dewram', ''),
(5, 'dulitha', ''),
(6, 'jayanaka', ''),
(7, 'shamal', ''),
(8, 'oshanda', ''),
(9, 'panduka', ''),
(10, 'pasan', ''),
(11, 'kavindu', ''),
(12, 'dian', '');

Configure the database.php file in CI according to your credentials.

Create a controller, model and a view to start the project. In my case,
Controller => Search.php
Model => Search_model.php
View => search_data.php

Like we have done in pagination tutorial, we have to fetch and display the records of the users with pagination. I'm not going to explain it here. If you want visit here;

Same model functions are used to paginate and same controller function is used to display the data. 

Model Code:

defined('BASEPATH') OR exit('No direct script access allowed');

class Search_model extends CI_Model{

    //getting users per page

    public function getUserPagintaion($limit, $start) {
            $this->db->limit($limit, $start);
            $query = $this->db->get();
            return $result = $query->result();        

    //getting users count

    public function getUserCount() {
            $this->db->select("COUNT(*) as num_row");
            $query = $this->db->get();
            $result = $query->result();
            return $result[0]->num_row;


Controller Code :

    public function __construct()

    //display data with CI pagination
    public function index() {

        $config['base_url'] = 'http://localhost/Projects/CISearch/Search/index';
        $config['total_rows'] = $this->Search_model->getUserCount();
        $config['per_page'] = 5;
        $config['uri_segment'] = 3;
        $config['full_tag_open'] = '<ul class="pagination">';
        $config['full_tag_close'] = '</ul>';
        $config['attributes'] = array('class' => 'page_link');
        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['first_tag_open'] = '<li>';
        $config['first_tag_close'] = '</li>';
        $config['prev_link'] = '&laquo';
        $config['prev_tag_open'] = '<li class="prev">';
        $config['prev_tag_close'] = '</li>';
        $config['next_link'] = '&raquo';
        $config['next_tag_open'] = '<li>';
        $config['next_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li>';
        $config['last_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="page-item active"><a href="#" class="page-link">';
        $config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
        $config['num_tag_open'] = '<li>';
        $config['num_tag_close'] = '</li>';
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['link'] = $this->pagination->create_links();
        $data['message'] = '';
        $data['records'] = $this->Search_model->getUserPagintaion($config['per_page'], $page);
        $this->load->view('search_data', $data);

View Code :

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>CI Search</title>
<link rel="stylesheet" href="" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link href="" rel="stylesheet">
    <style type="text/css">
        body {
            font-family: 'Roboto', sans-serif;

      <div class="container">

        <h1>CodeIgniter Search</h1>
        <?php echo form_open("Search/searchUser" , ['class' => 'form-inline']); ?>
            <div class="form-group">
              <input type="text" class="form-control" id="searchuser" name="search" placeholder="Type a name">
            <button type="submit" name="searchBtn" class="btn btn-primary submit">Search</button>
            <button class="btn btn-default more" href="<?php echo site_url('Search') ?>">Refresh</button>
        <?php echo form_close(); ?>
        <?php echo '<h3 style="color: #26324E;">'.$message.'</h3>';?>
        <div class="row">
            <div class="col-lg-12">
                <div class="table-responsive table-bordered">
                    <table class="table">


                    <?php if (count($records)): ?>

                    <?php foreach ($records as $row): ?>

                        <td><?php echo $row->indexno; ?></td>
                        <td><?php echo $row->username; ?></td>
                        <td><?php echo $row->email; ?></td>
                        <td><a href="#"><button type='submit' class='btn btn-primary'>update</button></a></td>
                        <td><a href="#"><button type='submit' class='btn btn-danger'>Delete</button></a></td>

                    <?php endforeach; ?>

                    <?php else: ?>
                        <center><p style="margin: 20px;">No users registered</p></center>
                    <?php endif ?>
                <?php echo $link ?>  
<script src="" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


Now you will be shown the records with page numbers.

The highlighted part is new and it is the search form that we use to search data from database. Now we have to implement the controller function to submit form data. Add the following code the controller.

    public function searchUser() {
        $key = $this->input->post('search');

        if(isset($key) and !empty($key)){
            $data['records'] = $this->Search_model->searchRecord($key);
            $data['link'] = '';
            $data['message'] = 'Search Results';
            $this->load->view('search_data' , $data);
        else {
            redirect('Search') ;

The colored words should be same as they defined in the search form. 
Search button name = search
Search controller function name = searchUser
Search model function name = searchRecord

When we consider the body of the function, it first get the data by data input and assign a variable to hold that data. Then the posted data is checked. If there's a key AND it is not empty; means you have typed something in search input field and submitted, data is fetched through the model function called searchRecord. It is passed to an array called data as a variable called records.
Then the pagination link is passed empty. If you do not include it here, CI will display an error saying undefined variable since we have included in index function to load the data from DB. When the page is reloading, this link should be passed to avoid errors. Then another variable is passed to data array called message which displays the phrase - "Search Results". After submitting the search form, this will be displayed on the top of the results. Finally you need to load the search_data page with the variable passed to data array. If records are not found, it will redirect to the main view.

Search Function in the Model : 

Add this code to the model

    public function searchRecord($key)
        $query = $this->db->get();

          return $query->result();

This function will return a array with data using a SQL query with LIKE option. Model searches for records where it matches with the key you have input in the search field. If you enter a username like "pool", it will display the all username records OR records matched with email or indexno that includes the entered word phrase. If results are found, num_rows function checks whether the count is greater than zero. If so, return the result. That's all...

Now you have completed my tutorial foe search data with CI. Try this article and you will be able to search records from a database. I hope you get the idea. If you need further clarifications, drop a comment here.
Good Luck!

No comments :