What are the best practices for querying multiple tables in PHP without using multiple SELECT queries in a for loop?

When querying multiple tables in PHP without using multiple SELECT queries in a for loop, it is best to use JOIN statements in a single SQL query to retrieve the required data in one go. This helps reduce the number of queries sent to the database, improving performance and reducing the complexity of the code.

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

// Query multiple tables using JOIN
$query = "SELECT t1.column1, t2.column2
          FROM table1 t1
          INNER 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);

// Process the results
foreach ($results as $result) {
    // Access data from different tables using $result['column_name']
    echo $result['column1'] . ' - ' . $result['column2'] . '<br>';
}
?>