What are some best practices for joining multiple tables in PHP to retrieve and display related information efficiently?

When joining multiple tables in PHP to retrieve and display related information efficiently, it is best to use SQL JOIN queries to combine data from different tables based on a related column. This allows for fetching all the necessary information in a single query rather than making multiple queries. Additionally, using proper indexing on the columns being joined can improve query performance.

<?php
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query with JOIN to retrieve related information from multiple tables
$sql = "SELECT users.username, orders.order_id, orders.total
        FROM users
        INNER JOIN orders ON users.user_id = orders.user_id";

$result = $conn->query($sql);

// Display the retrieved information
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Username: " . $row["username"]. " - Order ID: " . $row["order_id"]. " - Total: " . $row["total"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>