PHP-MySQL Lesson: The ORDER BY Clause

The ORDER BY Clause

In this lesson we are going to write PHP scripts that select a records in MySQL and sort it using the ORDER BY clause.

Using ORDER BY clause we can sort the data in a recordset in a ascending or descending order.

ASC – ascending order (default)
DESC – descending order

We can execute any sql query like insert, update, delete, select etc. using the mysql_query() function.Here is the code:

<?php
//including the database connection file
include("mysql_connect.php");
mysql_select_db("employee");
$result = mysql_query("SELECT * FROM employee_record ORDER BY f_name");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Position</th>
<th>Age</th>
<th>Salary</th>
<th>Email</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['f_name']."</td>";
echo "<td>".$row['l_name']."</td>";
echo "<td>".$row['position']."</td>";
echo "<td>".$row['age']."</td>";
echo "<td>".$row['salary']."</td>";
echo "<td>".$row['email']."</td>";
echo "</tr>";
}
echo "</table>";
?>

In the above example it will select all the data stored in our table and then sort it by f_name in an ascending order.

In our example we have used include() function, this function takes all the content in a specified file and includes it in the current file.

Then, we have selected the employee database using the mysql_select_db() function.

Next, we have declared a variable $result that will store the value returned by mysql_query() function.

Next, we use the mysql_fetch_array() function to fetch a row from a recordset as an array.

Then, we place the mysql_fetch_array() function within the conditional statement of the while loop. It means that the while loop will continue to execute as long as there a row to fetch.

Comments

comments

, ,

Post navigation

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.