Pagination with Search Filter in CodeIgniter 3

Pagination gets complicated when finding specific groups of records when there is a large number of records are available.

By adding a search filter with pagination makes it easier for the user to easily find records e.g. filter list by country, department, name, etc.

It is easier to add pagination using pagination library in CodeIgniter.

In this tutorial, I am using the SESSION to store search value and filter the pagination list.

Pagination with Search Filter in CodeIgniter 3


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. View
  6. Demo
  7. Conclusion

1. Table structure

I am using posts table.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Navigate to application/config/database.php and define Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

$autoload['libraries'] = array("database");

3. Model

Create a Main_model.php file in application/models/ directory.

Create 3 methods –

  • _construct
  • getData() – This methods takes 3 parameters.

Fetch records from posts table and if the $search is not empty then set search value in title and content fields.

Return an array.

  • getrecordCount() – This method return total records.

If the $search is not empty then search value in title and content field.

Return the allcount value.

Completed Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Main_model extends CI_Model {

  public function __construct() {
    parent::__construct(); 
  }

  // Fetch records
  public function getData($rowno,$rowperpage,$search="") {
 
    $this->db->select('*');
    $this->db->from('posts');

    if($search != ''){
      $this->db->like('title', $search);
      $this->db->or_like('content', $search);
    }

    $this->db->limit($rowperpage, $rowno); 
    $query = $this->db->get();
 
    return $query->result_array();
  }

  // Select total records
  public function getrecordCount($search = '') {

    $this->db->select('count(*) as allcount');
    $this->db->from('posts');
 
    if($search != ''){
      $this->db->like('title', $search);
      $this->db->or_like('content', $search);
    }

    $query = $this->db->get();
    $result = $query->result_array();
 
    return $result[0]['allcount'];
  }

}

4. Controller

Create a User.php file in application/controllers/ directory.

Create 3 methods –

  • __construct – Load session, pagination library and Main_model model.
  • index() – Redirect to loadRecord() method.
  • loadRecord() – If search form get post then read $this->input->post('search') and assign in $search_text.

Also, initialize the SESSION search variable with $search_text.

If <form> does not post then check SESSION initialized or not. If value is defined then assign SESSION variable value in $search_text.

Count and fetch records from Main_model.

Configuration pagination and initialize $data array.

Here, for displaying search value on search box define $data['search'] = $search_text.

Load user_view and pass the $data.

Completed Code

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

class User extends CI_Controller {

  public function __construct(){
 
    parent::__construct();
    $this->load->helper('url');

    // Load session
    $this->load->library('session');

    // Load Pagination library
    $this->load->library('pagination');

    // Load model
    $this->load->model('Main_model');
  }

  public function index(){
    redirect('User/loadRecord');
  }

  public function loadRecord($rowno=0){

    // Search text
    $search_text = "";
    if($this->input->post('submit') != NULL ){
      $search_text = $this->input->post('search');
      $this->session->set_userdata(array("search"=>$search_text));
    }else{
      if($this->session->userdata('search') != NULL){
        $search_text = $this->session->userdata('search');
      }
    }

    // Row per page
    $rowperpage = 5;

    // Row position
    if($rowno != 0){
      $rowno = ($rowno-1) * $rowperpage;
    }
 
    // All records count
    $allcount = $this->Main_model->getrecordCount($search_text);

    // Get records
    $users_record = $this->Main_model->getData($rowno,$rowperpage,$search_text);
 
    // Pagination Configuration
    $config['base_url'] = base_url().'index.php/User/loadRecord';
    $config['use_page_numbers'] = TRUE;
    $config['total_rows'] = $allcount;
    $config['per_page'] = $rowperpage;

    // Initialize
    $this->pagination->initialize($config);
 
    $data['pagination'] = $this->pagination->create_links();
    $data['result'] = $users_record;
    $data['row'] = $rowno;
    $data['search'] = $search_text;

    // Load view
    $this->load->view('user_view',$data);
 
  }

}

5. View

Create a user_view.php file application/views/ directory.

Create a search <form> where I added a search box and a submit button. Set <form> action to <?= base_url() ?>index.php/User/loadRecord.

List records from $result in <table>.

Display the generated pagination with $pagination.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Pagination with Search Filter in CodeIgniter 3</title>
  
    <style type="text/css">
    a {
     padding-left: 5px;
     padding-right: 5px;
     margin-left: 5px;
     margin-right: 5px;
    }
    </style>
  </head>
  <body>

   <!-- Search form (start) -->
   <form method='post' action="<?= base_url() ?>index.php/User/loadRecord" >
     <input type='text' name='search' value='<?= $search ?>'><input type='submit' name='submit' value='Submit'>
   </form>
   <br/>

   <!-- Posts List -->
   <table border='1' width='100%' style='border-collapse: collapse;'>
    <tr>
      <th>S.no</th>
      <th>Title</th>
      <th>Content</th>
    </tr>
    <?php 
    $sno = $row+1;
    foreach($result as $data){

      $content = substr($data['content'],0, 180)." ...";
      echo "<tr>";
      echo "<td>".$sno."</td>";
      echo "<td><a href='".$data['link']."' target='_blank'>".$data['title']."</a></td>";
      echo "<td>".$content."</td>";
      echo "</tr>";
      $sno++;

    }
    if(count($result) == 0){
      echo "<tr>";
      echo "<td colspan='3'>No record found.</td>";
      echo "</tr>";
    }
    ?>
   </table>

   <!-- Paginate -->
   <div style='margin-top: 10px;'>
   <?= $pagination; ?>
   </div>

 </body>
</html>

6. Demo

View Demo


7. Conclusion

I used the SESSION to store search value when <form > submit and use to filter records.

If you like to add more than one search element then add it in <form> and initialize the SESSION in the controller and use it.

You can view this tutorial to know pagination implementation in CodeIgniter 4.

If you found this tutorial helpful then don't forget to share.

20 thoughts on “Pagination with Search Filter in CodeIgniter 3”

  1. i have done all setting above mention but when i click on pagination link then search session value set as blank i don’t know whats problem
    please help me about that

    Reply
  2. could you help me? I have followed and checked my code with your code. but why besides the first page, the search results don’t display anything. even though there was data I was looking for

    Reply
  3. Can you help me to configure my search functionality?
    I’m trying to build one with multiple get parameters but I’m having lot of troubles as it requires to look into two DB tables using join and I’ve been unable to make it work..

    Please if you decide to help, answer me via email, thanks.(It is in CodeIgniter 3.9).

    Reply
  4. Building a simple app for a school. Your tutorials helped me a lot. Many Codeigniter search/pagination tutorials out there… This is the first one I’ve seen to use SESSIONS… Genius!

    Thanks!

    Reply

Leave a Comment