Sort data in MySQL using PHP

How to Sort Data in MySQL Using the ORDER BY Clause in PHP?

Order By clause is an another important clause. You can retrieve data in a particular order (ascending / descending). You can use order by clause on any column, you can use order by clause with more then one column too. The syntax is mentioned below: Syntax


SELECT column_name(s)
FROM table_name
ORDER BY column_name ASC|DESC
Example is mentioned below:

Code


<?php
  // Establish database connection
  $connection = mysqli_connect("localhost", "marcus", "xyz123", "my_database");

  // Check connection
  if (!$connection)
  {
    die("Could not connect with MySQL: " . mysqli_connect_error());
  }

  // Execute SELECT query with ORDER BY clause
  $result = mysqli_query($connection, "SELECT * FROM Employee ORDER BY FirstName ASC");

  // Check query execution
  if (!$result)
  {
    die("Error occurred: " . mysqli_error($connection));
  }

  // Fetch and display records
  while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
  {
    print($row["FirstName"] . " " . $row["LastName"] . " " . $row["PhoneNo"]);
    print("
"); } // Free result memory mysqli_free_result($result); // Close database connection mysqli_close($connection); ?>
The output of the above code will be:

Output


Edge    Boucher    35457845
Kane    Johnson    33457845

FAQ 1. Why is the ORDER BY clause important in MySQL? The ORDER BY clause helps organize database records in a meaningful order. It makes information easier to read, search and analyze, especially when displaying database records on web pages. 2. What is the difference between ASC and DESC in MySQL? ASC sorts records in ascending order, such as A to Z or 1 to 100. DESC sorts records in descending order, such as Z to A or 100 to 1.