Column Sorting using PHP and MySQL

Column Sorting using PHP and MySQL

In this post we will give you information about Column Sorting using PHP and MySQL. Hear we will give you detail about Column Sorting using PHP and MySQLAnd how to use it also give you demo for it if it is necessary.

In this example, i will show you simple way to create table column sorting from database using php mysql. we will do it sorting column by clicking column header with php and mysql in table.

It is a very basic example for php starter to create column sort ascending descending order by click on column heading. It is very simple way to create without using ajax. so we can create this example in a single file.

in this example we will create “countries” with name and code column. Then after will create one index file and manage column sorting. You can simply see below preview of this example.


Create countries table:

Here, we will create countries table by following sql query:



'name' varchar(80) NOT NULL,

'code' varchar(244) NOT NULL,



Create index.php file:

Also see:PHP – Jquery Chosen Ajax Autocomplete Example

<!DOCTYPE html>



<title>Column Sorting using PHP and MySQL -</title>

<link rel="stylesheet" href="" />



<div >

<h1>Column Sorting using PHP and MySQL -</h1>


$hostName = "localhost";

$username = "root";

$password = "root";

$dbname = "test";

$mysqli = new mysqli($hostName, $username, $password, $dbname);

$orderBy = !empty($_GET["orderby"]) ? $_GET["orderby"] : "name";

$order = !empty($_GET["order"]) ? $_GET["order"] : "asc";

$sql = "SELECT * FROM countries ORDER BY " . $orderBy . " " . $order;

$result = $mysqli->query($sql);

$nameOrder = "asc";

$codeOrder = "asc";

if($orderBy == "name" && $order == "asc") {

$nameOrder = "desc";


if($orderBy == "code" && $order == "asc") {

$codeOrder = "desc";



<table >



<th><a href="?orderby=name&order=<?php echo $nameOrder; ?>">Name</a></th>

<th><a href="?orderby=code&order=<?php echo $codeOrder; ?>">Code</a></th>





while($row = mysqli_fetch_assoc($result)){



<td><?php echo $row['name']; ?></td>

<td><?php echo $row['code']; ?></td>










Now you can simply run.

I hope it can help you….

Hope this code and post will helped you for implement Column Sorting using PHP and MySQL. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

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

8  +  1  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US