PHP MySQL Order by

Source: Internet
Author: User
Tags php mysql php programming

The ORDER BY keyword is used to sort the data in the recordset.

ORDER by keyword

The ORDER BY keyword is used to sort the data in the recordset.

The ORDER BY keyword defaults to sorting the records in ascending order.

If you want to sort in descending order, use the DESC keyword.

Grammar

SELECT column_name (s) from Table_nameorder by column_name (s) asc| DESC

Instance

The following instance selects all the data stored in the "Persons" table and sorts the results according to the "Age" column:

<?php$con=mysqli_connect ("example.com", "Peter", "abc123", "my_db");//Check connectionif (Mysqli_connect_errno () {echo "Failed to connect to MySQL:"). Mysqli_connect_error ();} $result = Mysqli_query ($con, "select * from Persons ORDER by age") and while ($row = Mysqli_fetch_array ($result)) {echo $row [' Fi Rstname '];echo "". $row [' LastName '];echo "". $row [' Age '];echo ' <br> ';} Mysqli_close ($con);? >

The above results will be output:

Glenn Quagmire 33Peter Griffin 35

Sort by two columns

You can sort by more than one column. When sorting by more than one column, the second column is used only when the first column has the same value:

SELECT column_name (s) from Table_nameorder by Column1, Column2

Related reading:

PHP Programming Notes Sharing-very practical

PHP MySQL Order by

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.