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


Contents

  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` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `publish_date` date 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");

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() {
    parent::__construct(); 
  }

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

    $this->db->select('*');
    $this->db->from('posts');
    $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');
    $this->db->from('posts');
    $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

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

class Post 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('Post/loadRecord');
  }

  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 ){
      $this->session->set_userdata(array("sortBy"=>$sortBy));
      $this->session->set_userdata(array("order"=>$order));
    }else{
      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
    $this->pagination->initialize($config);

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

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

  }

}

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

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <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;
    }
    </style>
  </head>
  <body>

    <?php

    // Set order
    if($order == "asc"){
      $order = "desc";
    }else{
      $order = "asc";
    }
    ?>
    <!-- Posts List -->
    <table border='1' width='100%' style='border-collapse: collapse;'>
      <tr>
       <th>S.no</th>

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

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

       <th>
         <!-- 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>
       </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 "<td>".$data['publish_date']."</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

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.