How to ORDER the output from a table.
TAGS: SQL, ORDER BY, PHP, MySQL


Now I will show how to ORDER the output from a query.
We order the output by choosing a field from our table that we want to order the query after. In our example database this can be for example the AutoID field, swhere each row is given a unique number. We can also order the listing we make by ORDER BY Lastname, or whatever we have in our database.

In this example we ORDER BY AutoID. We can choose to order from low numbers to higher numbers (older to newer). Or we can make the listing go from high numbers to lower numbers (newer to older rows).
This is done by the ASC or DESC, as you see in the code below. If you use ASC/DESC in fields containing characters it will order from A-Z (ASC), or Z-A (DESC).

Now create a .php file and name it 'orderby.php'. Paste in the code below, and then open it in your browser.

http://127.0.0.1/orderby.php

<?php 
$con = mysqli_connect('127.0.0.1', 'root', 'Your_Password', 'dbname'); 

if (mysqli_connect_errno()) { 
  echo 'Error connecting to DB'; 
} 

$SQL_String = mysqli_query(
$con, 'SELECT * FROM contacts ORDER BY AutoID DESC'); 

while($row = mysqli_fetch_array($SQL_String))  { 
  echo '

You will see the AutoID number printet before the name of your contacts in the table we use in our examples.
Then try to change the SQL string in this example, and write ASC instead of DESC. Load the page again, and now, in the listing, you should see your contacts listed from the lowest number to the higher numbers.