PHP MySQL Use The ORDER BY Clause
To retrieve data from a MySQL database in a specific order using the ORDER BY clause
Select and Order Data From a MySQL Database
The ORDER BY clause is used to sort the result-set in ascending or descending order.
The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Select and Order Data From a MySQL Database
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Using MySQLi:
<?php // MySQLi Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name // Create connection $conn = new mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // SQL statement with ORDER BY clause $sql = "SELECT * FROM users ORDER BY name ASC"; // Orders by name in ascending order // Execute the query $result = $conn->query($sql); // Check if there are any rows returned if ($result->num_rows > 0) { // Output data of each row while ($row = $result->fetch_assoc()) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "You can click on above box to edit the code and run again.
"; } } else { echo "0 results"; } // Close connection $conn->close(); ?>
Output
Using PDO :
<?php // PDO Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name try { // Connect to MySQL using PDO $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); // Set PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // SQL statement with ORDER BY clause $sql = "SELECT * FROM users ORDER BY name ASC"; // Orders by name in ascending order // Prepare the statement $stmt = $conn->prepare($sql); // Execute the statement $stmt->execute(); // Fetch all rows as associative array $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Output data of each row foreach ($rows as $row) { echo "ID: " . $row["id"] . " - Name: " . $row["name"] . " - Email: " . $row["email"] . "You can click on above box to edit the code and run again.
"; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Close connection $conn = null; ?>
Output
In both examples:
The ORDER BY clause is used to sort the result set.
The ASC keyword sorts the result set in ascending order. You can use DESC for descending order.
Adjust the column name and order as needed for your use case.