How can PHP be used to retrieve and display data from a MySQL database sorted by date?
To retrieve and display data from a MySQL database sorted by date using PHP, you can use a SQL query with an ORDER BY clause that sorts the data based on the date column. You can then fetch the results and display them in your desired format.
<?php
// Connect to MySQL 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);
}
// Select data from database sorted by date
$sql = "SELECT * FROM table_name ORDER BY date_column DESC";
$result = $conn->query($sql);
// Display the sorted data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Date: " . $row["date"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
Related Questions
- What are some potential pitfalls when comparing large arrays in PHP, as described in the forum thread?
- How can developers effectively debug issues with DOMXPath queries in PHP?
- What steps can be taken to troubleshoot and debug PHP code to identify the root cause of unexpected behavior like automatic redirection?