What is the recommended method for displaying the 5 latest entries from a database on a website using PHP?
To display the 5 latest entries from a database on a website using PHP, you can retrieve the entries from the database in descending order based on a timestamp or ID, limit the results to 5, and then display them on the website. This can be achieved by writing a SQL query to fetch the data and then iterating over the results to display them on the webpage.
<?php
// 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);
}
// Fetch the 5 latest entries from the database
$sql = "SELECT * FROM entries ORDER BY timestamp DESC LIMIT 5";
$result = $conn->query($sql);
// Display the entries on the webpage
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Entry ID: " . $row["id"]. " - Content: " . $row["content"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are some potential pitfalls or errors that may arise when using $array[0]->$name in PHP?
- Welche potenziellen Probleme können auftreten, wenn man versucht, eine interne Umleitung auf ein PHP-Skript mit .htaccess durchzuführen?
- What alternative methods can be used to track progress in a PHP script if a progress bar is not feasible?