How can you display the last 5 entries from a database in a PHP forum thread?
To display the last 5 entries from a database in a PHP forum thread, you can retrieve the entries using a SQL query with an ORDER BY clause to sort them in descending order based on a timestamp or an auto-incremented ID. Then, limit the results to 5 entries using the LIMIT clause. Finally, loop through the results and display each entry in the forum thread.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "forum";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve the last 5 entries from the database
$sql = "SELECT * FROM entries ORDER BY entry_id DESC LIMIT 5";
$result = $conn->query($sql);
// Display the entries in the forum thread
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div class='entry'>";
echo "<p>" . $row['content'] . "</p>";
echo "<p>Posted by: " . $row['author'] . "</p>";
echo "</div>";
}
} else {
echo "No entries found.";
}
// Close the database connection
$conn->close();
?>
Related Questions
- How can the configuration of the database server and the web server affect the ability to access a database on a different server using PHP?
- What are potential pitfalls when storing JSON strings in a PHP database?
- What are the best practices for accessing PHP files through a web browser using localhost?