How can the SQL ORDER BY clause be utilized to sort data before outputting it in PHP?
To sort data before outputting it in PHP, you can use the SQL ORDER BY clause in your SQL query to specify the column by which you want to sort the results. This allows you to retrieve the data already sorted from the database before displaying it in your PHP script.
<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to select data from table and order by a specific column
$sql = "SELECT * FROM table_name ORDER BY column_name ASC";
$result = $conn->query($sql);
// Output sorted data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column 1: " . $row["column1"]. " - Column 2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>