What best practices should be followed when using PHP to display data from multiple tables in a hierarchical structure?

When displaying data from multiple tables in a hierarchical structure using PHP, it is important to properly organize the data and ensure that the relationships between the tables are correctly established. One common approach is to use SQL JOIN statements to fetch data from multiple tables based on their relationships. Additionally, using nested loops or recursive functions can help in displaying the data in a hierarchical manner.

<?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);
}

// Fetch data using SQL JOIN
$sql = "SELECT * FROM parent_table
        LEFT JOIN child_table ON parent_table.parent_id = child_table.parent_id";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Display data in a hierarchical structure
    while($row = $result->fetch_assoc()) {
        echo "Parent: " . $row["parent_column"] . "<br>";
        echo "  Child: " . $row["child_column"] . "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();
?>