Membership
Main Menu
Forum Boards
Stats
- 18 tutorials
- 72,338 members
- 696,813 forum posts
- 11 blog posts
Tutorials
PHP Basic Database Handling
Views: 57648
Dealing With The Database: ORDER BY
In this block of code, we are going to decide how to order our list.
02. When we display the list, We make the column titles into links. The user can click on that column title to reorder the list by that title. Like the "delete" links, we pass how the user wants to sort the list through the url, using the GET method. So the first thing we do is check to see if that variable exists. If it does...
04. Remember when we talked about preventing sql injection? Another method to restrict what is being sent to your database, is to specify what is allowed. This is called making a white list. It's just like in the real world when something is black listed or white listed. If it's in the array, it's allowed. Everything else is not. Making a white list is generally more secure than making a black list. So anyways, this is our array of allowed column names to sort. If the $_GET['orderby'] is not one of those columns, we assign a default column.
06. Since we are making a white list of columns, using mysql_real_escape_string is technically pointless. If someone tried to use escape quotes or other such things, it wouldn't be on our list anyways. I don't really have a logical reason for doing it, other than it somehow makes me feel like it's more secure.
08. Here is where we check to see if the value being passed to us is a valid column. We're going to assign something to $order no matter what, but depending on whether it's valid or not, we will either keep it as is or assign a default. We use a ternary operator to do this. The condition is evaluated inside the ( )'s. If it is true, we assign what's on the left of the : if it's false, we assign what's on the right.
11. The else statement is to assign a default column if a column title was not clicked. The default will usually be assigned from this else statement if the user is going to the page for the first time, or if the user clicked on something other than the column title (like a delete link or the form submit button).
