Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Sql Mysql-example PHP SQL ORDER BY

Related Tutorials


 
 

Share on Google+Share on Google+

PHP SQL ORDER BY

Advertisement
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:

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 20, 2009

Related Tutorials

Discuss: PHP SQL ORDER BY   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com