Sorting Database Results with PHP
(Page 1 of 2 )
This tutorial will show you how to display data from a database and allow the user to sort it.
I've been asked many times to write a tutorial that explains how to display data from a database and gives the user an option to sort the data by different columns. So, here it is!
The method of doing this is, in fact, very simple. When you display your data, just make each column heading clickable and have it pass the column name as a value. Then, when you make your query, use that value in the ORDER BY clause and display the data again.
You will see in the script that I am about to present to you, that it is good practice to specify a default value for the ORDER BY in case nothing has been chosen yet. I also add some error checking to make sure that the value for the ORDER BY clause is an acceptable value and won't cause the query to fail. This is accomplished by placing all acceptable values in an array and checking the passed in value against that.
The array that I just mentioned is also used to decide whether a particular column is a column we want sorted when we display the data.
Anyway, I'll just let the script do the rest of the talking. It is commented fairly well and should be self explanatory. If you do have any questions, always feel free to ask them in the forums!
Next: The Code >>
More Database Articles Articles
More By Matt Wade