How can you simplify complex SQL queries when dealing with tables and foreign keys in PHP?

When dealing with complex SQL queries involving tables and foreign keys in PHP, one way to simplify the process is to use JOIN statements to combine related tables into a single query. This allows you to retrieve data from multiple tables in a single query, reducing the need for multiple queries and improving performance.

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

// Query to retrieve data from multiple tables using JOIN
$sql = "SELECT t1.column1, t2.column2
        FROM table1 t1
        JOIN table2 t2 ON t1.foreign_key = t2.id
        WHERE t1.some_condition = 'value'";

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

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

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