PHP MySQL Order By


Putting the Result Set in Order

To see data from a table ordered by a particular field, use the ORDER BY clause in conjunction with the SELECT argument. The ORDER BY clause allows you to specify which field to sort against and whether to sort ascending or descending.


This clause's basic syntax can be summed up as follows:


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


Let's create a SQL query that uses the ORDER BY clause in the SELECT statement, and then run it through the PHP mysqli query() function to get the ordered results.


The PHP code in the following example selects all rows from the persons table and sorts the results alphabetically ascending by the first name column.


<?php
  /* Attempt MySQL server connection. Assuming you are running MySQL
  server with default setting (user 'root' with no password) */
  $mysqli = new mysqli("localhost", "root", "", "demo");

  // Check connection
  if($mysqli === false){
  die("ERROR: Could not connect. " . $mysqli->connect_error);
  }

  // Attempt select query execution with order by clause
  $sql = "SELECT * FROM persons ORDER BY first_name";
  if($result = $mysqli->query($sql)){
  if($result->num_rows > 0){
  echo "<table>";
  echo "<tr>";
  echo "<th>id</th>";
  echo "<th>first_name</th>";
  echo "<th>last_name</th>";
  echo "<th>email</th>";
  echo "</tr>";
  while($row = $result->fetch_array()){
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
  echo "<td>" . $row['first_name'] . "</td>";
  echo "<td>" . $row['last_name'] . "</td>";
  echo "<td>" . $row['email'] . "</td>";
  echo "</tr>";
  }
  echo "</table>";
  // Free result set
  $result->free();
  }
  else{
    echo "No records matching your query were found.";
  }
  }
  else{
    echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
  }

  // Close connection
  $mysqli->close();
?>