The `ORDER BY` clause in MySQL is used to sort the result set based on one or more columns. When you're working with PHP to fetch and display data from a MySQL database, you'll often use the `ORDER BY` clause to present the data in a meaningful order. Let's break down the aspects of using the `ORDER BY` clause with PHP and MySQL:
To sort the result set of a query by a specific column:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1;
By default, `ORDER BY` sorts in ascending order. To specify the sort direction, you can use the `ASC` (ascending) or `DESC` (descending) keywords.
ORDER BY column1 DESC;
You can sort by multiple columns by separating column names with commas:
ORDER BY column1, column2 DESC;
This will sort by `column1` in ascending order first and then by `column2` in descending order for rows that have the same `column1` value.
Suppose you have a table called `users` with the columns `id`, `first_name`, `last_name`, and `age`. To retrieve users sorted by last name in ascending order:
<?php
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "my_database";
// Create connection
$conn = new mysqli($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select data
$sql = "SELECT id, first_name, last_name, age FROM users ORDER BY last_name ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row["last_name"]. " - Age: " . $row["age"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Note: Remember to replace the placeholders like "username", "password", etc., with your actual database connection details. This is a very basic way to fetch and display data from a MySQL database using PHP. In a real-world scenario, you'd also want to consider security measures, such as using prepared statements, to protect against SQL injection attacks.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here