Skip to content
PHP Logo

What are the best practices for handling data aggregation and display in PHP when dealing with multiple related tables?

When dealing with multiple related tables in PHP, it is best practice to use SQL JOIN statements to aggregate data from different tables and then display the results in a structured format. This allows you to retrieve data from multiple tables in a single query and present it in a cohesive manner.

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

// Query to retrieve data from multiple related tables using JOIN
$query = "SELECT users.username, orders.order_id, orders.total_amount
          FROM users
          JOIN orders ON users.user_id = orders.user_id";

// Execute the query
$stmt = $pdo->query($query);

// Display the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "Username: " . $row['username'] . "<br>";
    echo "Order ID: " . $row['order_id'] . "<br>";
    echo "Total Amount: $" . $row['total_amount'] . "<br><br>";
}
?>