What are some best practices for implementing a news system in PHP, specifically for displaying the latest news from a database on a website's homepage?
Issue: To display the latest news from a database on a website's homepage in PHP, you can create a news system that retrieves the latest news entries from the database and displays them in a user-friendly format on the homepage. PHP Code Snippet:
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "news_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve latest news entries from the database
$sql = "SELECT * FROM news_table ORDER BY date_published DESC LIMIT 5";
$result = $conn->query($sql);
// Display the news entries on the homepage
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<p>" . $row["content"] . "</p>";
echo "<p><em>Published on: " . $row["date_published"] . "</em></p>";
echo "<hr>";
}
} else {
echo "No news entries found.";
}
$conn->close();
?>
Keywords
Related Questions
- What are the advantages of using absolute paths over relative paths in HTML when dealing with downloads in PHP?
- What are the drawbacks of using the ereg function in PHP, considering it is deprecated?
- Is it possible to deactivate a selected option in a radio button group if a text field is filled out instead?