0% found this document useful (0 votes)
21 views2 pages

PHP Bab 28 PHP Mysql Order

The document discusses how to use the ORDER BY keyword in SQL to sort data retrieved from a table. The ORDER BY keyword is used with the SELECT statement and sorts the records in ascending order by default or descending if the DESC keyword is specified. It is also possible to order by multiple columns.

Uploaded by

Farhan Aziz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

PHP Bab 28 PHP Mysql Order

The document discusses how to use the ORDER BY keyword in SQL to sort data retrieved from a table. The ORDER BY keyword is used with the SELECT statement and sorts the records in ascending order by default or descending if the DESC keyword is specified. It is also possible to order by multiple columns.

Uploaded by

Farhan Aziz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

PHP MySQL Order By Keyword

The ORDER BY keyword is used to sort the data in a recordset.

The ORDER BY Keyword

The ORDER BY keyword is used to sort the data in a recordset.

Syntax

SELECT column_name(s)
FROM table_name
ORDER BY column_name

Note: SQL statements are not case sensitive. ORDER BY is the same as order by.

Example

The following example selects all the data stored in the "Person"
table, and sorts the result by the "Age" column:

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

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM person ORDER BY age");

while($row = mysql_fetch_array($result))
{
echo $row['FirstName']
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br />";
}
mysql_close($con);
?>

The output of the code above will be:

Glenn Quagmire 33
Peter Griffin 35

Sort Ascending or Descending

28-1
If you use the ORDER BY keyword, the sort-order of the recordset is ascending by default (1
before 9 and "a" before "p").

Use the DESC keyword to specify a descending sort-order (9 before 1


and "p" before "a"):

SELECT column_name(s)
FROM table_name
ORDER BY column_name DESC

Order by Two Columns

It is possible to order by more than one column. When ordering by


more than one column, the second column is only used if the values
in the first column are identical:

SELECT column_name(s)
FROM table_name
ORDER BY column_name1, column_name2

28-2

You might also like