How can JOIN be used to optimize multiple SQL queries into a single query in PHP?

Using JOIN in SQL allows you to combine data from multiple tables into a single result set, which can optimize multiple SQL queries into a single query. By joining tables on related columns, you can retrieve all the necessary data in one go, reducing the number of queries and improving performance.

<?php
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password');

// Query with JOIN to retrieve data from multiple tables
$query = "SELECT table1.column1, table2.column2
          FROM table1
          JOIN table2 ON table1.id = table2.table1_id
          WHERE table1.condition = 'value'";

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

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

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