How can PHP be integrated with database queries to optimize performance when displaying new forum posts?

To optimize performance when displaying new forum posts, one can use PHP to efficiently query the database for the latest posts and display them in a timely manner. This can be achieved by using prepared statements to prevent SQL injection attacks, caching query results to reduce database load, and limiting the number of posts retrieved to only what is necessary for the current page.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=forum', 'username', 'password');

// Prepare a query to select the latest forum posts
$stmt = $pdo->prepare("SELECT * FROM posts ORDER BY created_at DESC LIMIT 10");
$stmt->execute();

// Fetch and display the latest forum posts
while ($row = $stmt->fetch()) {
    echo "<div>{$row['title']}</div>";
    echo "<div>{$row['content']}</div>";
    echo "<div>{$row['created_at']}</div>";
}