Pagination in CodeIgniter


Pagination is the most required feature in the web application. Generally, pagination is useful when data is retrieved from the database and listed in the web page. Pagination in data list is mandatory when you need to list the huge data. It helps to load data faster and make your web application user-friendly.

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

For the example purpose, we will fetch the posts data from the database and list this records with pagination link. The following functionality will be implemented to demonstrate CodeIgniter pagination.

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

Create Database Table

The posts table contains some basic fields to store the post data.

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

Controller (Posts.php)

The Posts controller consists of 2 methods, __construct() and index().
__construct()

  • Load Pagination library.
  • Load Post model.
  • Specify pagination limit (per page).

index()

  • Get total rows count using getRows() method of Post model.
  • Specify the configuration in $config array for Pagination class.
  • Initialize the Pagination class with your preferred options using initialize() method.
  • Define offset by the page URI.
  • Get rows from posts table using getRows() method of Post model.
  • Pass the posts data to view and load the list view.

Some configuration options are specified for styling the pagination links with Bootstrap. You can omit this configuration (styling) if want to use basic style.

<?php if ( ! defined('BASEPATH')) 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 4;
    }
    
    public function 
index(){
        
$data = array();
        
        
//get rows count
        
$conditions['returnType'] = 'count';
        
$totalRec $this->post->getRows($conditions);
        
        
//pagination config
        
$config['base_url']    = base_url().'posts/index/';
        
$config['uri_segment'] = 3;
        
$config['total_rows']  = $totalRec;
        
$config['per_page']    = $this->perPage;
        
        
//styling
        
$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>';
        
        
//initialize pagination library
        
$this->pagination->initialize($config);
        
        
//define offset
        
$page $this->uri->segment(3);
        
$offset = !$page?0:$page;
        
        
//get rows
        
$conditions['returnType'] = '';
        
$conditions['start'] = $offset;
        
$conditions['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. The getRows() function fetch the records from posts table based on the limit restriction provided in the $params array and returns posts data as an array.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class 
Post extends CI_Model{
    
/*
     * Get posts
     */
    
function getRows($params = array()){
        
$this->db->select('*');
        
$this->db->from('posts');
        if(
array_key_exists("id",$params)){
            
$this->db->where('id',$params['id']);
            
$query $this->db->get();
            
$result $query->row_array();
        }else{
            
//set start and limit
            
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']);
            }
            
            if(
array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
                
$result $this->db->count_all_results();
            }else{
                
$query $this->db->get();
                
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }

        
//return fetched data
        
return $result;
    }
}

View (posts/)

The view folder (posts/) contains index.php file to list the paginated data.

index.php
The bootstrap library is used for styling the posts lists and pagination links. So, include the Bootstrap library first. If you want to use basic style, don’t need to include it.

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

In index.php file, the posts data are listed with the pagination links. The create_links() function of Pagination class generates the pagination links.

<div class="panel panel-default ">
    <div class="panel-heading">Posts </div>
    <div class="panel-body">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th width="5%">ID</th>
                    <th width="30%">Title</th>
                    <th width="65%">Content</th>
                </tr>
            </thead>
            <tbody id="userData">
                <?php if(!empty($posts)): foreach($posts as $post): ?>
                <tr>
                    <td><?php echo '#'.$post['id']; ?></td>
                    <td><?php echo $post['title']; ?></td>
                    <td><?php echo (strlen($post['content'])>150)?substr($post['content'],0,150).'...':$post['content']; ?></td>
                </tr>
                <?php endforeach; else: ?>
                <tr><td colspan="3">Post(s) not found......</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<!-- render pagination links -->
<ul class="pagination pull-right">
    <?php echo $this->pagination->create_links(); ?>
</ul>

Ajax Pagination with Search and Filter in CodeIgniter

Conclusion

CodeIgniter’s Pagination library is easy to use and customize. Here we have shown a basic pagination example in CodeIgniter application. However, you can easily customize this pagination code as per your requirement. If you want to integrate an Ajax pagination in CodeIgniter, follow this tutorial – Ajax Pagination in Codeigniter Framework

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

Recommended Tutorials For You

Leave a reply