PHPMySQLOrderBy keyword usage
- SELECT column_name (s)
- FROM table_name
- Order by column_name
-
Note: SQL is case insensitive. Order by is equivalent to order. For example, select all the data stored in the "Persons" table and sort the results according to the "Age" column:
$ Con = mysql_connect ("localhost", "peter", "abc123 ");
- If (! $ Con)
- {
- Die ('could not connect: '. mysql_error ());
- }
Mysql_select_db ("my_db", $ con );
$ Result = mysql_query ("SELECT * FROM Persons order by age ");
While ($ row = mysql_fetch_array ($ result ))
- {
- Echo $ row ['firstname'];
- Echo "". $ row ['lastname'];
- Echo "". $ row ['age'];
- Echo"
";
- }
Mysql_close ($ con );
- ?>
Output: Glenn Quagmire 33 Peter Griffin 35 1. sort in ascending or descending ORDER if you use the order by keyword, the sorting ORDER of the record set is ascending BY default (1 before 9, "a" before "p ). Use the DESC keyword to set the descending order (9 before 1, "p" before "):
- SELECT column_name (s)
- FROM table_name
- Order by column_name DESC
2. Sort by two columns by multiple columns. When sorting by multiple columns, the second column is used only when the first column is the same:
- SELECT column_name (s)
- FROM table_name
- Order by column_name1, column_name2
|