What are the common pitfalls when using multiple database queries in PHP, especially when trying to retrieve and display related data?

When using multiple database queries in PHP to retrieve and display related data, a common pitfall is making separate queries for each related piece of data, leading to inefficient code and potential performance issues. To solve this, it's recommended to use JOIN queries to fetch all related data in a single query, reducing the number of database calls and improving overall performance.

// Example of using JOIN query to retrieve related data
$query = "SELECT users.id, users.name, orders.order_id, orders.total_amount 
          FROM users
          JOIN orders ON users.id = orders.user_id
          WHERE users.id = 1";

$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0){
    while($row = mysqli_fetch_assoc($result)){
        echo "User ID: " . $row['id'] . "<br>";
        echo "User Name: " . $row['name'] . "<br>";
        echo "Order ID: " . $row['order_id'] . "<br>";
        echo "Total Amount: " . $row['total_amount'] . "<br>";
    }
} else {
    echo "No results found.";
}