What are some best practices for optimizing PHP code when dealing with multiple database queries?

When dealing with multiple database queries in PHP, it is important to optimize the code to improve performance. One best practice is to minimize the number of queries by combining related queries into a single query using JOIN statements or subqueries. Additionally, consider using prepared statements to prevent SQL injection attacks and improve query execution speed.

// Example of optimizing multiple database queries by combining them into a single query using JOIN

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

// Query to fetch user information and their orders
$query = "SELECT users.name, orders.order_id, orders.total_amount 
          FROM users 
          JOIN orders ON users.user_id = orders.user_id 
          WHERE users.user_id = :user_id";

// Prepare the statement
$stmt = $pdo->prepare($query);

// Bind the user_id parameter
$user_id = 1;
$stmt->bindParam(':user_id', $user_id);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Output the results
foreach ($results as $row) {
    echo "User: " . $row['name'] . " | Order ID: " . $row['order_id'] . " | Total Amount: " . $row['total_amount'] . "<br>";
}