What are the advantages of using ORDER BY in a SQL query when fetching data in PHP?
Using ORDER BY in a SQL query allows you to sort the fetched data in a specific order, such as ascending or descending based on a column. This is useful when you want to display the data in a particular order on your webpage. By specifying the order in the SQL query, you can ensure that the data is presented in a meaningful way to the user.
// 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);
}
// Fetch data from database ordered by a specific column
$sql = "SELECT * FROM table_name ORDER BY column_name DESC";
$result = $conn->query($sql);
// Display fetched 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";
}
// Close connection
$conn->close();