How can PHP developers optimize their code for querying and displaying results from multiple tables efficiently?

When querying and displaying results from multiple tables in PHP, developers can optimize their code by using JOIN statements in their SQL queries to fetch data from related tables in a single query. This reduces the number of queries executed and improves performance by minimizing database interactions.

<?php
// Establish a database connection
$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 and display results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['column1'] . ' - ' . $row['column2'] . '<br>';
}
?>