How can the ORDER BY clause in a MySQL query affect the output of data displayed in a PHP script?
When using the ORDER BY clause in a MySQL query, the data returned will be sorted based on the specified column(s) in either ascending or descending order. This can affect the output of data displayed in a PHP script by changing the order in which the data is presented to the user. To ensure that the data is displayed in the desired order, you can specify the ORDER BY clause in your MySQL query with the appropriate column and sorting direction.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM table_name ORDER BY column_name ASC"; // Change column_name and ASC/DESC as needed
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>