Create jQuery Sort Table by Column Value with PHP

In this tutorial, you will learn how to create jQuery sort table with PHP. As a PHP developer, we often need to implement sorting with table column by values, so here in this tutorial I have used a  jQuery plugin Tablesorter to handle column sorting in a table.

Also, read:

Here are easy steps to create jQuery sorted table with PHP.

jquery sort table

 


1. Include jQuery and Tablesorter Plugin

To use the tablesorter plugin to create sorted table, you need to include the jQuery library and the tablesorter plugin. So you first need to download Tablesorter and put into your project directory. Then include plugin file with jQuery latest file.

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="tablesorter/jquery.tablesorter.min.js"></script>

2. HTML Structure for Table

As the tablesorter plugin works on standard HTML tables. You must need to include THEAD and TBODY tags. So here I have created HTML structure with data from MySQL database table using PHP.

<table id="sortTable" class="tablesorter">
<thead>
<tr>
<th>Employee Id</th>
<th>Employee Name</th>
<th>Salary</th>
<th>Age(Years)</th>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT id, employee_name, employee_salary, employee_age 
FROM employee LIMIT 10";
$resultset = mysqli_query($conn, $sql) or 
die("database error:". mysqli_error($conn));
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<tr>
<td><?php echo $rows["id"]; ?></td>
<td><?php echo $rows["employee_name"]; ?></td>
<td>$<?php echo $rows["employee_salary"]; ?></td>
<td><?php echo $rows["employee_age"]; ?></td>
</tr>
<?php } ?>
</tbody>
</table>

3. Now Sort table with Tablesorter

After creating HTML table structure, now it’s time to tell tablesorter plugin to sort your table when the document is loaded:

<script>
$(document).ready(function() {
$("#sortTable").tablesorter();
}
);
</script>

You may also like:

You can see view the complete running example from the demo link. You can also download complete demo script from below links.


Demo Download

2 thoughts on “Create jQuery Sort Table by Column Value with PHP

Leave a Reply

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