How can the ORDER BY clause in a MySQL query be used to sort entries by date in PHP?
To sort entries by date in a MySQL query using the ORDER BY clause in PHP, you can specify the column containing the date values and the desired sorting order (ASC for ascending or DESC for descending). This allows you to retrieve the data in a specific order based on the dates stored in the database.
// Connect to the 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);
}
// Query to select entries sorted by date in descending order
$sql = "SELECT * FROM table_name ORDER BY date_column DESC";
$result = $conn->query($sql);
// Fetch and display the sorted data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Date: " . $row["date_column"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();