Pagination in CodeIgniter

Pagination is the most required feature in the data list of the web application. Generally, pagination is used when data is retrieved from the database and listed on the web page. The pagination feature is very useful to list the huge number of dynamic records from the database. It helps to load data faster and make the web application user-friendly.

If your web application built with the CodeIgniter framework, it’s very easy to implement pagination in the data list. CodeIgniter provides the Pagination class to create pagination links for the results set. In this tutorial, we will provide a step-by-step guide to implement pagination functionality in CodeIgniter using Pagination library.

In the example CodeIgniter pagination script, we will fetch the posts data from the database and list the records with pagination links. The following functionality will be implemented to demonstrate pagination in CodeIgniter framework.

  • Retrieve data from the MySQL database.
  • Create pagination links using Pagination library.
  • List the records with pagination links.

Pagination in PHP with MySQL

Create Database Table

To store the post’s data a table is required in the database. The following SQL creates a posts table with some basic fields in the MySQL database.

CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Controller (Posts.php)

The Posts controller generates the pagination links and loads the data list view.

  • __construct()
    • Load the Pagination library.
    • Load the Post model.
    • Define the limit of records to display per page.
  • index()
    • Get the total record count using getRows() method of Post model.
    • Specify the configuration in $config array for pagination.
    • Initialize the Pagination class with the configuration options using initialize() method.
    • Define offset by the page URI segment.
    • Fetch records from the database using getRows() method of Post model.
    • Pass the posts data and load the list view.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 

class 
Posts extends CI_Controller {
    
    function 
__construct() {
        
parent::__construct();
        
        
// Load pagination library
        
$this->load->library('pagination');
        
        
// Load post model
        
$this->load->model('post');
        
        
// Per page limit
        
$this->perPage 10;
    }
    
    public function 
index(){
        
$data $conditions = array();
        
$uriSegment 3;
        
        
// Get record count
        
$conditions['returnType'] = 'count';
        
$totalRec $this->post->getRows($conditions);
        
        
// Pagination configuration
        
$config['base_url']    = base_url().'posts/index/';
        
$config['uri_segment'] = $uriSegment;
        
$config['total_rows']  = $totalRec;
        
$config['per_page']    = $this->perPage;
        
        
// Initialize pagination library
        
$this->pagination->initialize($config);
        
        
// Define offset
        
$page $this->uri->segment($uriSegment);
        
$offset = !$page?0:$page;
        
        
// Get records
        
$conditions = array(
            
'start' => $offset,
            
'limit' => $this->perPage
        
);
        
$data['posts'] = $this->post->getRows($conditions);
        
        
// Load the list page view
        
$this->load->view('posts/index'$data);
    }
}

Model (Post.php)

The Post model is used to retrieve posts data from the database.

  • getRows() – Fetch the records from posts table based on the conditions provided in the $params array. Returns data as an array.
<?php defined('BASEPATH') OR exit('No direct script access allowed'); 

class 
Post extends CI_Model{
    
    function 
__construct() {
        
// Set table name
        
$this->table 'posts';
    }
    
    
/*
     * Fetch records from the database
     * @param array filter data based on the passed parameters
     */
    
function getRows($params = array()){
        
$this->db->select('*');
        
$this->db->from($this->table);
        
        if(
array_key_exists("where"$params)){
            foreach(
$params['where'] as $key => $val){
                
$this->db->where($key$val);
            }
        }
        
        if(
array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
            
$result $this->db->count_all_results();
        }else{
            if(
array_key_exists("id"$params) || (array_key_exists("returnType"$params) && $params['returnType'] == 'single')){
                if(!empty(
$params['id'])){
                    
$this->db->where('id'$params['id']);
                }
                
$query $this->db->get();
                
$result $query->row_array();
            }else{
                
$this->db->order_by('id''desc');
                if(
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    
$this->db->limit($params['limit'],$params['start']);
                }elseif(!
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    
$this->db->limit($params['limit']);
                }
                
                
$query $this->db->get();
                
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }
        
        
// Return fetched data
        
return $result;
    }
}

View (posts/)

The posts/ folder holds the view files of the Posts controller.

index.php
In the index.php file, the posts data are listed with the pagination links.

  • The create_links() function of Pagination class generates the pagination links.
<!-- Display posts list -->
<div class="post-list">
<?php if(!empty($posts)){ foreach($posts as $row){ ?>
    <div class="list-item"><a href="javascript:void(0);"><?php echo $row["title"]; ?></a></div>
<?php } }else{ ?>
    <p>Post(s) not found...</p>
<?php ?>
</div>

<!-- Render pagination links -->
<div class="pagination">
    <?php echo $this->pagination->create_links(); ?>
</div>

Customize the Pagination Links

The CodeIgniter Pagination class provides various configuration options to customize the pagination links. The link tags customization option is very useful to apply the Bootstrap style for navigation links of CodeIgniter pagination. In the following example, we will show how you can design the CodeIgniter pagination with Bootstrap library.

Controller:
Specify the tags in configuration options for styling the pagination links with Bootstrap.

// Pagination link format 
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a href="javascript:void(0);">';
$config['cur_tag_close'] = '</a></li>';
$config['next_link'] = 'Next';
$config['prev_link'] = 'Prev';
$config['next_tag_open'] = '<li class="pg-next">';
$config['next_tag_close'] = '</li>';
$config['prev_tag_open'] = '<li class="pg-prev">';
$config['prev_tag_close'] = '</li>';
$config['first_tag_open'] = '<li>';
$config['first_tag_close'] = '</li>';
$config['last_tag_open'] = '<li>';
$config['last_tag_close'] = '</li>';

View:
Include the Bootstrap library on the web page where the pagination links will render.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Ajax Pagination with Search and Filter in CodeIgniter

Conclusion

CodeIgniter’s Pagination library is the easiest way to add pagination to the data list and customize the pagination links as per the web page UI. Here we have shown a basic pagination example in CodeIgniter application. You can easily enhance the functionality of this pagination code as per your needs. If you want to make the pagination user-friendly, integrate Ajax pagination in CodeIgniter.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

4 Comments

  1. Ehtezaz Ahemd Said...
  2. Atul Chauhan Said...
  3. Arnav Anand Said...
  4. Tahseen Ullah Said...

Leave a reply

keyboard_double_arrow_up