Make pagination with CodeIgniter Framework

Pagination on the page improves the user experience when there is a large number of records are available.

CodeIgniter has provided a library for effectively handle the pagination functionality.

In this tutorial, I am using the pagination library to create the paginated list of fetched result from MySQL database.

Make pagination with CodeIgniter Framework


Contents

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

1. Table structure

I am using users table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Navigate to application/config/database.php and define the 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");

Remove index.php from URL

Navigate to application/config/config.php and replace $config['index'] = "index.php"; with $config["index"] = "";.

  • Create .htaccess file in your project root directory.
  • Write the following code in it –
RewriteEngine On
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]

3. Model

Create a new User_model.php file in application/models/directory.

Create two function getData() and getrecordCount().

  • getData() – Fetch and return records from users table according to the $rowno and $rowperpage value.
  • getrecordCount() – Return total records in users table.

Completed Code

<?php 

if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class User_Model extends CI_Model {

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

 // Fetch records 
 public function getData($rowno,$rowperpage) { 
   $this->db->select('*'); 
   $this->db->from('users');        
   $this->db->limit($rowperpage, $rowno);    
   $query = $this->db->get();        
   return $query->result_array(); 
 }

 // Select total records    
 public function getrecordCount() {
   $this->db->select('count(*) as allcount');      
   $this->db->from('users');      
   $query = $this->db->get();      
   $result = $query->result_array();            
   return $result[0]['allcount'];    
 }
}

4. Controller

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

Define a constructor, index(), and loadRecord() methods.

  • __construct() – Load pagination library using $this->load->library() and User_model.
  • index() – Redirect to loadRecord() method.
  • loadRecord() – Set $rowperpage to 5 and if $rowno value is not equal to 0 then $rowno = ($rowno-1) * $rowperpage.

Get the total records by calling getrecordCount() method and user records by calling getData() method where pass $rowno and $rowperpage value.

Set the pagination configuration.

Pass the $config to $this->pagination->initialize($config) and get the links with $this->pagination->create_links() and initialize $data['pagination'].

Pass the $user_record in $data['result'] and $rowno in $data['row'].

Load the user_view and pass the $data variable.

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 Pagination library 
   $this->load->library('pagination');
   
   // Load model 
   $this->load->model('User_model'); 
 } 

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

 public function loadRecord($rowno=0){
   // Row per page 
   $rowperpage = 5;
   
   // Row position 
   if($rowno != 0){ 
     $rowno = ($rowno-1) * $rowperpage; 
   }            

   // All records count      
   $allcount = $this->User_model->getrecordCount();

   // Get  records      
   $users_record = $this->User_model->getData($rowno,$rowperpage);   
         
   // Pagination Configuration      
   $config['base_url'] = base_url().'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;

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

5. View

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

Display users record by looping on the $result variable and display pagination link with $pagination in <div>.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="utf-8"> <title>CodeIgniter</title>
  <style type="text/css"> 
  a { 
   padding-left: 5px; 
   padding-right: 5px; 
   margin-left: 5px; 
   margin-right: 5px; 
  } 
  </style>
 </head>
 <body>
  <table border='1' style='border-collapse: collapse;'> 
   <tr> 
    <th>S.no</th> 
    <th>Username</th> 
    <th>Name</th> 
    <th>Email</th> 
   </tr> 
   <?php  
    $sno = $row+1; 
    foreach($result as $data){ 
      echo "<tr>"; 
      echo "<td>".$sno."</td>"; 
      echo "<td>".$data['username']."</td>"; 
      echo "<td>".$data['name']."</td>"; 
      echo "<td>".$data['email']."</td>"; 
      echo "</tr>"; 
      $sno++; 
    } 
    ?> 
  </table>
  <!-- Paginate --> 
  <div style='margin-top: 10px;'> 
  <?= $pagination; ?> 
  </div>
 </body>
</html>

6. Conclusion

You need to load the pagination library and set the required configuration for initializing. Then create the paginate numeric links and use it in the view.

I have only used some of the configurations for the pagination library you can learn more about it from here.

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