How can JOINs be utilized to optimize the performance of PHP scripts when querying multiple tables?

Using JOINs in SQL queries can optimize the performance of PHP scripts when querying multiple tables by reducing the number of queries needed to retrieve data from related tables. By joining tables based on common columns, we can retrieve all necessary data in a single query instead of making multiple queries and then combining the results in PHP.

<?php
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Query using JOIN to retrieve data from multiple tables
$query = "SELECT users.username, orders.order_id, orders.total_amount 
          FROM users 
          JOIN orders ON users.user_id = orders.user_id";
$stmt = $pdo->query($query);

// Fetch and display the results
while ($row = $stmt->fetch()) {
    echo "Username: " . $row['username'] . " | Order ID: " . $row['order_id'] . " | Total Amount: " . $row['total_amount'] . "<br>";
}
?>