Sort Pagination records on Header Click in CodeIgniter

Pagination is used to display the large list of records in multiple pages form. This makes easier to access records.

You can make traversing more easier by add sorting on the table.

The table list gets arranged according to the clicked header.

In this tutorial, I show how you can implement pagination sorting on header click in CodeIgniter.

Sort Pagination records on Header Click in CodeIgniter


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

1. Table structure

I am using posts table in the example and added some records.

CREATE TABLE `posts` (
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `publish_date` date NOT NULL

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");

3. Model

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

Here, create 3 methods –

  • __construct – Constructor.
  • getData() – Fetch records form posts table. Use $rowno and $rowperpage in limit and $sortBy and $order to order the records.
  • getrecordCount() – Return total number of records in posts table.

Completed Code

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

Class Main_model extends CI_Model {

  public function __construct() {

  // Fetch records 
  public function getData($rowno,$rowperpage,$sortBy,$order) {

    $this->db->order_by($sortBy, $order);
    $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');
    $query = $this->db->get();
    $result = $query->result_array();

    return $result[0]['allcount'];


4. Controller

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

Here, create 3 methods –

  • __construct – Load url helper, session library, pagination library, and Main_model model.
  • index – Redirect to loadRecord method.
  • loadRecord – This method takes 3 parameter – $rowno, $sortBy, and $order.Set $rowperpage = 5 and update $rowno value if not equal to 0.

Check if column-name passed on URL or not. If passed then create sortBy and order session variables and initialize with $sortBy and $order.

Otherwise, assign session values to $sortBy and $order if the session is set.

Get the total number of records by calling Main_model->getrecordCount() method. Pass $rowno,$rowperpage,$sortBy,$order in Main_moder->getData() method to fetch records.

Configure pagination and initialize $data array with $this->pagination->create_links(), $posts_record, $rowno, and $order.

Load user_view view and pass $data.

Completed Code

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

class Post extends CI_Controller {

  public function __construct(){

    // Load session
    // Load Pagination library

    // Load model

  public function index(){

  public function loadRecord($rowno=0,$sortBy="id",$order="asc"){

    // Row per page
    $rowperpage = 5;
    // Row position 
    if($rowno != 0){ 
       $rowno = ($rowno-1) * $rowperpage; 
    // Set session
    if($this->uri->segment('4') != NULL ){
      if($this->session->userdata('sortBy') != NULL){
        $sortBy = $this->session->userdata('sortBy');
        $order = $this->session->userdata('order');

    // Total records count
    $allcount = $this->Main_model->getrecordCount();

    // Get records
    $posts_record = $this->Main_model->getData($rowno,$rowperpage,$sortBy,$order);

    // Pagination Configuration
    $config['base_url'] = base_url().'index.php/Post/loadRecord';
    $config['use_page_numbers'] = TRUE;
    $config['total_rows'] = $allcount;
    $config['per_page'] = $rowperpage;

    // Initialize

    $data['pagination'] = $this->pagination->create_links();
    $data['result'] = $posts_record;
    $data['row'] = $rowno;
    $data['order'] = $order;

    // Load view



5. View

Create a post_view.php file in application/views/ directory.

Toggle $order value and create <table > to list records. On the header column add <a > for sorting.

Point <a > link to loadRecords() method and also pass 3 values pagination-index, column name, and order.

Loop on $result to create <tr> and use <div > to display the pagination link.

Completed Code

defined('BASEPATH') OR exit('No direct script access allowed');
<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <title>Sort Pagination records on Header Click in CodeIgniter</title>

    <style type="text/css">
    a {
      padding-left: 5px;
      padding-right: 5px;
      margin-left: 5px;
      margin-right: 5px;


    // Set order
    if($order == "asc"){
      $order = "desc";
      $order = "asc";
    <!-- Posts List -->
    <table border='1' width='100%' style='border-collapse: collapse;'>

         <!-- index.php/controller/method-name/pagination-index/column-name/order -->
         <a href='<?= base_url() ?>index.php/Post/loadRecord/0/title/<?= $order ?>'>Title</a>

         <!-- index.php/controller/method-name/pagination-index/column-name/order -->
         <a href='<?= base_url() ?>index.php/Post/loadRecord/0/content/<?= $order ?>'>Content</a>

         <!-- index.php/controller/method-name/pagination-index/column-name/order -->
         <a href='<?= base_url() ?>index.php/Post/loadRecord/0/publish_date/<?= $order ?>'>Publish Date</a>
     $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 "<td>".$data['publish_date']."</td>";
       echo "</tr>";

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

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


6. Demo

Click on column name – Title, content, or Publish date to sort the list.

7. Conclusion

I used the anchor tag on the table header for sorting the pagination list. Within the anchor link passed column-name, and sorting order.

When it gets clicked read values and fetch records accordingly.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.