How can I efficiently retrieve and display posts from the last 2 weeks in PHP using MySQL?
To efficiently retrieve and display posts from the last 2 weeks in PHP using MySQL, you can use the following approach: - Get the current date and calculate the date from 2 weeks ago. - Query the database for posts that have a timestamp within the last 2 weeks. - Display the retrieved posts on the webpage.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Calculate date from 2 weeks ago
$twoWeeksAgo = date('Y-m-d', strtotime('-2 weeks'));
// Query database for posts from the last 2 weeks
$sql = "SELECT * FROM posts WHERE post_date >= '$twoWeeksAgo'";
$result = $conn->query($sql);
// Display posts
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Title: " . $row["title"]. " - Content: " . $row["content"]. "<br>";
}
} else {
echo "No posts found from the last 2 weeks.";
}
// Close database connection
$conn->close();
?>
Keywords
Related Questions
- What are the advantages and disadvantages of storing files directly on the web server versus storing file paths in a database in PHP applications?
- How can PHP developers ensure proper code structure and adherence to the E-V-A principle when implementing header modifications for redirection?
- How can one validate file uploads in PHP to ensure security?