How to Sort a Field of a MySQL Table in Ascending Order in PHP


In this article, we will show how you can sort any field of a MySQL in ascending order. This means in alphabetical order for alphabetical characters and in numerical order for number values.

This can be for any column of a table. Putting values in ascending order is important for a wide variety of applications.

Think about a site such as travelocity. After you've entered in the data for the flight you are looking for and the site has processed the data to enter matching flights, you now have a bunch of flights returned to you. You can now order the sites by price, from cheapest to most expensive, by airline name (A-Z), and many different factors. These are applications that sorting a column in ascending order have. They can list a column in the exact order which a user wants to view them by cheapest to most expensive, shortest to longest flight duration, airline name (A-Z), etc.


An example of this is a table below of snack foods, where the table is arranged in order of the price:


You can see how the snack items are arranged in order of their price.


So how do we sort a column in ascending order with PHP?

Once you've connected to a MySQL server and database and display a table, you may want to have that table sorted in a particular order. Let's say we have a database of airline ticket prices and we want to show the database in the order of cheapest tickets to most expensive. We now specify the column of the table, in this case, price, and put them in ascending order by the command ORDER BY price.

The format for putting code in ascending order, numerically for number lists and alphabetically for word lists, is:

$result = mysql_query( "SELECT * FROM $table ORDER BY column_name" )
or die("SELECT Error: ".mysql_error());

Below is the full code of organizing a database by a column in ascending order, the most important line allowing this, highlighted in red:

The first block of code is where you place in your hostname, user name, password, database name, and table name of the MySQL server, database, and table, that you want to connect to.

The second block of code connects you to the MySQL server and the database of in the MySQL server that you want to connect to.

The third block of code selects the table that is desired to be viewed and lists the rows of that table in ascending order by price, from least to greatest.

The fourth block of code prints outs the table with the conditions specified above.

Related Resources

How to Select Specific Columns from a MySQL Table Using PHP

How to Display Certain Fields of a Table in MySQL Using PHP

How to Select a Specific Row of a MySQL Table Using PHP

How to Find the Number of Rows in a MySQL Table Using PHP

HTML Comment Box is loading comments...