Sort table data in ascending or descending order in Codeigniter

This tutorial shows how to sort table data either in ascending or descending order by clicking on the table column header in Codeigniter 2.1.x. There are no. of client side ajax based jquery or javascript table sorter plugins are available in the market. But here I will show you how you can achieve the the same sorting functionality without using javascript or jquery.
Final output should be

When column data sorted in ascending order
sort table data in codeigniter

When column data sorted in descending order
sort table data in codeigniter

So let’s see how to code for it

Create MySQL table

CREATE TABLE `items` (
  `item_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `item_name` varchar(45) COLLATE latin1_general_ci NOT NULL,
  `item_desc` text COLLATE latin1_general_ci,
  `item_price` double unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`item_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

 

Insert some data into the table

insert  into `items`(`item_id`,`item_name`,`item_desc`,`item_price`)
values (1,'CD','CD is a compact disk',100),
(2,'DVD','DVD is larger than CD in size',150),
(3,'ABC','ABC test description',24),
(4,'XYZ','XYZ test description',25.32),
(5,'CD Player','CD player is used to play CD',30.02);

 

View – item_list.php

<title>Table column sorting in asc or desc example in Codeigniter</title>    
        <?php
        if ($item_list) {
            ?><?php
                    $i = 0;
                    foreach ($item_list as $item) {
                        $col_class = ($i % 2 == 0 ? 'odd_col' : 'even_col');
                        ?><?php
                        $i++;
                    }
                    ?>
        <table class="datatable">
            <thead>
            <tr><th <?php if ($sort_by == 'item_name') echo ?> class="\&quot;sort_$sort_order\&quot;&quot;">
                            <?php
                            echo anchor("items/item_list/item_name/" .
                                    (($sort_order == 'ASC' && $sort_by == 'item_name') ? 'DESC' : 'ASC'), 'Name');
                            ?>
                        </th><th <?php if ($sort_by == 'item_desc') echo ?> class="\&quot;sort_$sort_order\&quot;&quot;">
                            <?php
                            echo anchor("items/item_list/item_desc/" .
                                    (($sort_order == 'ASC' && $sort_by == 'item_desc') ? 'DESC' : 'ASC'), 'Description');
                            ?>
                        </th><th <?php if ($sort_by == 'item_price') echo ?> class="\&quot;sort_$sort_order\&quot;&quot;">
                            <?php
                            echo anchor("items/item_list/item_price/" .
                                    (($sort_order == 'ASC' && $sort_by == 'item_price') ? 'DESC' : 'ASC'), 'Price');
                            ?>
                        </th>
                    </tr>
                </thead>
                    <tbody>
                    <tr class="<?php echo $col_class; ?>">
                    <td>
                                <?php echo $item->item_name; ?>
                            </td>
                    <td>
                                <?php echo $item->item_desc; ?>
                            </td>
                    <td>
                                <?php echo $item->item_price; ?>
                            </td>
                        </tr>
                </tbody>
            </table>
            <?php
        } else {
            echo '<div style="color:red;"><p>No Record Found!</p></div>';
        }
        ?>

 

Look at the view file carefully. We have only hyperlink to each column header for sorting purpose. We have css class attached to each header to identify whether this is a current sorted header and by what order. Also we are checking whether the sort order is ascendending or decending. By default the sort order is ascending.

Inside foreach loop we have assigned row class either as odd_col or as even_col and accordingly changes the background.

I have included one css file in the <head/> section to apply some basic style for the table. The css source code is given below.

table.datatable {
    width:100%;
    border: none;
    background:#fff;
}
table.datatable td.table_foot {
    border: none;
    background: #fff;
    text-align: center;
}
table.datatable tr.odd_col {
    background: none;
}
table.datatable tr.even_col {
    background: #ddd;
}
table.datatable td {
    font-size:10pt;
    padding:5px 10px;
    border-bottom:1px solid #ddd;
    text-align: left;
}
table.datatable th {
    text-align: left;
    font-size: 8pt;
    padding: 10px 10px 7px;   
    text-transform: uppercase;
    color: #fff;
    background:url(../img/table/head.gif) left -5px repeat-x;
    font-family: sans-serif;
}
table.datatable th a{
    color: #fff;
}
table.datatable th.sort_ASC:after {
    content: "▲";
}
table.datatable th.sort_DESC:after {
    content: "▼";
}

 

Controller – items.php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Items extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this----->load->model('item_model', 'item');
    }
    public function index() {
        redirect('items/item_list');
    }
    function item_list($sort_by = 'item_name', $sort_order = 'ASC') {
        $results = $this->item->get_item_list($sort_by, $sort_order);
        $data['item_list'] = $results['item_list'];
        $data['sort_by'] = $sort_by;
        $data['sort_order'] = $sort_order;
        $this->load->view('item_list', $data);
    }
}
/* End of file items.php */
/* Location: ./application/controllers/items.php */

 

By default the function item_list sorts the column data based on item_name in ascending order.

Model – item_model.php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Item_Model extends CI_Model {
    private $items = 'items';
    function __construct() {
        
    }
    function get_item_list($sort_by, $sort_order) {
        $sort_order = ($sort_order == 'DESC') ? 'DESC' : 'ASC';
        $sort_columns = array('item_name', 'item_desc', 'item_price');
        $sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'item_name';
        $sql = 'SELECT item_id, item_name, item_desc, item_price
            FROM ' . $this----->items . ' ORDER BY ' . $sort_by . ' ' . $sort_order;
        $query = $this->db->query($sql);
        $result['item_list'] = $query->result();        
        return $result;
    }
}
/* End of file item_model.php */
/* Location: ./application/models/item_model.php */

 

In the model we check for sort order and the default is ASC. We put the columns which will be sorted, in an array. We check the the column name for sort by, default value is item_name.
Then we run the query.

Download the attached below image which you need for table header.

sort table data in codeigniter
Thanks for your reading. Please leave a comment because comment helps us to improve.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *