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


Insert some data into the table


View – item_list.php


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.


Controller – items.php


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

Model – 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 Twitter Facebook  Google Plus Linkedin

Leave a Reply

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