How can the JOIN statement in SQL be utilized to improve the efficiency of PHP scripts that involve multiple tables?

When dealing with multiple tables in PHP scripts, using the JOIN statement in SQL can significantly improve efficiency by reducing the number of queries needed to fetch related data. By joining tables in the database query, you can retrieve all necessary information in a single query rather than making multiple queries to fetch data from different tables separately.

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

// Query to fetch data from multiple tables using JOIN
$query = "SELECT t1.column1, t2.column2
          FROM table1 t1
          JOIN table2 t2 ON t1.id = t2.id";

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

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

// Loop through the results and do something with the data
foreach($results as $result) {
    echo $result['column1'] . " - " . $result['column2'] . "<br>";
}
?>