pTutorial

New way to learn PHP

PHP 5 MYSQL order clause

How to used order clause

Order by clause is basically used for sorting the record in PHP MYSQ.(descending or ascending order).

Syntax of order by clause


SELECT *FROM table_name
ORDER BY column_name(s) ASC|DESC

The given query fetch selected record in that table

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC

Where ASC is used for Aascending and DESC is used for descending order.

Example of order by


<?php

$user = "root";
$pwd = "";
$host = "localhost";
$db = @mysql_connect($host,$user,$pwd) or die("Connection failed");
mysql_select_db("my_db1") or die ("could not select the database");
echo "connection estsblished<br>";
$query="SELECT *from  student
ORDER BY name DESC";
$a=mysql_query($query,$db) or die("Execution of query failed!!!");
if(! $a )
{
die('Could not get data: ' . mysql_error());
}
echo "====================";
while($row = mysql_fetch_array($a))
{
echo "<br>Name :{$row['name']}  <br> ".
"Branch: {$row['branch']} <br> ";
} 
echo "====================";
echo"<br>Query Fetched";
mysql_close($db);

?>

Output

connection estsblished
====================
Name :xyz
Branch: ma

Name :harry
Branch: cse

Name :Brown
Branch: Ece
====================
Query Fetched

Another example of order by


<?php

$db = @mysql_connect("localhost","root","");
mysql_select_db("my_db1");
$query="SELECT name from  student
ORDER BY name ASC";
$a=mysql_query($query,$db) or die("Execution of query failed!!!");
if(! $a )
{
die('Could not get data: ' . mysql_error());
}
echo "====================";
while($row = mysql_fetch_array($a))
{
echo "<br>Name :{$row['name']}  <br> ";
} 
echo "====================";
mysql_close($db);

?>




Explanation

mysql_error() function is used to display the mysql error.


QUOTES OF THE DAY

We live in this world when we love it.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER