What are the best practices for displaying nested data from multiple database tables in PHP?
When displaying nested data from multiple database tables in PHP, it is best to use SQL JOIN queries to fetch the related data from different tables in a single query. This way, you can avoid making multiple queries and improve performance. Once you have fetched the nested data, you can then iterate over the results and display the data in a structured format.
// Assume we have two tables: users and orders
// We want to display user information along with their orders
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
// Fetch user information along with their orders using a JOIN query
$stmt = $pdo->prepare("SELECT users.*, orders.* FROM users JOIN orders ON users.id = orders.user_id");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display the nested data
foreach ($users as $user) {
echo "User ID: " . $user['id'] . "<br>";
echo "Name: " . $user['name'] . "<br>";
echo "Email: " . $user['email'] . "<br>";
echo "Orders: <br>";
echo "<ul>";
echo "<li>Order ID: " . $user['order_id'] . "</li>";
echo "<li>Product: " . $user['product'] . "</li>";
echo "<li>Quantity: " . $user['quantity'] . "</li>";
echo "</ul>";
}