Home > Backend Development > PHP Tutorial > Usage of PHP MySQL Order By keyword

Usage of PHP MySQL Order By keyword

WBOY
Release: 2016-07-25 08:55:00
Original
984 people have browsed it
  1. SELECT column_name(s)
  2. FROM table_name
  3. ORDER BY column_name
Copy code

Note: SQL is not case sensitive. ORDER BY is equivalent to order by.

Example, select all data stored in the "Persons" table and sort the results according to the "Age" column:

  1. $con = mysql_connect("localhost","peter","abc123");

  2. if (!$con)
  3. {
  4. die('Could not connect : ' . mysql_error());
  5. }

  6. mysql_select_db("my_db", $con);

  7. $result = mysql_query("SELECT * FROM Persons ORDER BY age");

  8. while($row = mysql_fetch_array($result))

  9. {
  10. echo $row['FirstName'];
  11. echo " " . $row['LastName' ];
  12. echo " " . $row['Age'];
  13. echo "
    ";
  14. }

  15. mysql_close($con);

  16. ?>< /p>
Copy the code

output: Glenn Quagmire 33 Peter Griffin 35

1, sorting in ascending or descending order If you use the ORDER BY keyword, the sort order of the recordset is ascending by default (1 before 9, "a" before "p").

Please use the DESC keyword to set descending order (9 comes before 1, "p" comes before "a"):

  1. SELECT column_name(s)
  2. FROM table_name
  3. ORDER BY column_name DESC
Copy code

2, sort based on two columns You can sort based on multiple columns. When sorting by multiple columns, the second column is used only if the first column is the same:

  1. SELECT column_name(s)
  2. FROM table_name
  3. ORDER BY column_name1, column_name2
Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template