What are the potential pitfalls of using multiple SQL queries in PHP to fetch and display forum data like in the provided code?

Using multiple SQL queries to fetch and display forum data can lead to performance issues, as each query adds overhead to the database connection. To solve this, you can use a single SQL query with JOINs to fetch all necessary data in one go, reducing the number of queries executed.

// Fetch forum data using a single SQL query with JOINs
$sql = "SELECT posts.id, posts.title, posts.content, users.username 
        FROM posts 
        INNER JOIN users ON posts.user_id = users.id 
        ORDER BY posts.created_at DESC";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // Display forum data
        echo "Title: " . $row["title"]. "<br>";
        echo "Content: " . $row["content"]. "<br>";
        echo "Author: " . $row["username"]. "<br>";
        echo "<hr>";
    }
} else {
    echo "No posts found.";
}