What are some best practices for optimizing PHP scripts that involve fetching data from multiple database tables?

When fetching data from multiple database tables in PHP scripts, it is important to optimize the queries to minimize the number of database calls and reduce the amount of data transferred. One way to achieve this is by using JOIN statements in SQL queries to fetch data from multiple tables in a single query rather than making separate queries for each table.

// Example of optimizing PHP script fetching data from multiple database tables using JOIN

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

// Query to fetch data from multiple tables using JOIN
$query = "SELECT users.username, orders.order_id, orders.total_amount 
          FROM users 
          INNER JOIN orders ON users.user_id = orders.user_id";

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

// Loop through the results
while ($row = $result->fetch_assoc()) {
    // Process the data
    echo "Username: " . $row['username'] . " | Order ID: " . $row['order_id'] . " | Total Amount: " . $row['total_amount'] . "<br>";
}

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