What are some best practices for debugging SQL queries in PHP, especially when dealing with multiple table joins?

When debugging SQL queries in PHP, especially when dealing with multiple table joins, it's important to break down the query into smaller parts and test each part individually to identify any errors. Use tools like var_dump() or print_r() to inspect the query results and make sure the data is being retrieved correctly. Additionally, consider using aliases for table names to make the query more readable and easier to debug.

<?php

// Example SQL query with multiple table joins
$query = "SELECT users.name, orders.order_date FROM users
          JOIN orders ON users.id = orders.user_id
          WHERE users.active = 1";

// Break down the query into smaller parts
$usersQuery = "SELECT name FROM users WHERE active = 1";
$ordersQuery = "SELECT order_date FROM orders";

// Test each part of the query individually
$resultUsers = $pdo->query($usersQuery);
$resultOrders = $pdo->query($ordersQuery);

// Use var_dump() to inspect the query results
var_dump($resultUsers->fetchAll());
var_dump($resultOrders->fetchAll());

?>