Home > Backend Development > PHP Tutorial > PHP MySQL Order By,phpmysqlorderby_PHP教程

PHP MySQL Order By,phpmysqlorderby_PHP教程

WBOY
Release: 2016-07-12 08:51:21
Original
944 people have browsed it

PHP MySQL Order By, phpmysqlorderby

ORDER BY keyword is used to sort the data in the record set.

ORDER BY keyword

ORDER BY keyword is used to sort the data in the record set.

ORDER BY keyword sorts records in ascending order by default.

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

Grammar

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
Copy after login

Example

The following example selects all data stored in the "Persons" table and sorts the results based on the "Age" column:

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons ORDER BY age");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'];
echo " " . $row['LastName'];
echo " " . $row['Age'];
echo "<br>";
}

mysqli_close($con);
?>
Copy after login

The above result will be output:

<code class="hljs nginx"><span class="hljs-title">Glenn Quagmire <span class="hljs-number">33
Peter Griffin <span class="hljs-number">35</span></span></span></code>
Copy after login

Sort based on two columns

Can be sorted based on multiple columns. When sorting by multiple columns, the second column is used only if the first column has the same value:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
Copy after login

Related reading:

PHP programming note sharing - very practical

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1130668.htmlTechArticlePHP MySQL Order By, phpmysqlorderby ORDER BY keyword is used to sort the data in the record set. ORDER BY keyword The ORDER BY keyword is used to sort data in a recordset. ...
Related labels:
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