What are some best practices for optimizing PHP scripts that involve multiple database queries?

When dealing with PHP scripts that involve multiple database queries, it's important to optimize the code to reduce the number of queries and improve performance. One way to achieve this is by using joins in SQL queries to combine related data into a single query result, rather than making separate queries for each piece of data.

// Example of optimizing multiple database queries using joins

// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Query to retrieve data using joins
$query = "SELECT users.username, orders.order_id, orders.total_amount 
          FROM users 
          JOIN orders ON users.user_id = orders.user_id";

$result = $connection->query($query);

// Process the query result
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "Username: " . $row['username'] . " | Order ID: " . $row['order_id'] . " | Total Amount: " . $row['total_amount'] . "<br>";
    }
} else {
    echo "No results found.";
}

// Close the database connection
$connection->close();