What are the potential pitfalls of joining multiple tables in a single query in PHP?

Joining multiple tables in a single query in PHP can lead to performance issues, especially if the tables contain a large amount of data. To mitigate this, it's important to optimize the query by only selecting the necessary columns, using proper indexing, and limiting the number of joins.

// Example of optimizing a query with multiple table joins
$query = "SELECT users.name, orders.product_name 
          FROM users 
          JOIN orders ON users.id = orders.user_id 
          WHERE users.id = :user_id";

$stmt = $pdo->prepare($query);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();

// Fetching the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Process the results
}