PHP SQL ORDER BY

Ads
 

PHP SQL ORDER BY

ORDER BY clause is used to sort the result data either in the ascending order or descending order. By default, the it is taken in ascending order.

ORDER BY clause is used to sort the result data either in the ascending order or descending order. By default, the it is taken in ascending order.

PHP SQL ORDER BY

     

This example illustrates how to execute query with ORDER BY clause in the php application.

ORDER BY clause is used to sort the result data either in the ascending order or descending order. By default, the it is taken in ascending order. ASC keyword can be used explicitly for ascending order. To make the order in descending order, "DESC" keyword is used. ORDER BY clause is used in conjunction with the name of the column based on which the sorting is performed.

In this example, we have created a sqlorderby.php file in which we executed a query to fetch the employee list in descending order. First, connection from database is created using mysql_connect("hostName", "userName", "Password"), selected the database by mysql_select_db("databaseName", connectionObject). Now, the query "SELECT * FROM emp ORDER BY name DESC" is executed to get the desired result. This query returns the the rows in the descending order of name.

 

 

Table: emp

Source Code of sqlorderby.php 

<?php
  $con = mysql_connect("localhost","root","root");
  if (!$con) {
  die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("test", $con);
  $result = mysql_query("SELECT * FROM emp ORDER BY name DESC");
  echo "<table border='1'>
  <tr>
  <th>Emp_Id</th>
  <th>Name</th>
  </tr>";
  while ($row = mysql_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['emp_id'] "</td>";
  echo "<td>" . $row['name'] "</td>";
  echo "</tr>";
  }
  echo "</table>";
  
  mysql_close($con);
?>

Download Source Code

Output:

 

Ads

Ads