What are some common methods for displaying hierarchical data from a MySQL database in PHP?
When displaying hierarchical data from a MySQL database in PHP, one common method is to use a recursive function to traverse the tree structure. Another approach is to use nested loops to iterate through parent-child relationships. Additionally, utilizing SQL queries with the "ORDER BY" clause can help organize the data in a hierarchical manner.
// Recursive function to display hierarchical data
function displayHierarchy($parent_id, $level = 0) {
$result = mysqli_query($connection, "SELECT * FROM table WHERE parent_id = $parent_id");
while ($row = mysqli_fetch_assoc($result)) {
echo str_repeat('-', $level) . $row['name'] . "<br>";
displayHierarchy($row['id'], $level + 1);
}
}
// Call the function with the root parent_id
displayHierarchy(0);
Keywords
Related Questions
- What best practices should be followed when fetching and outputting data from a database using PHP?
- What are the best practices for reading and writing to files in PHP, especially when dealing with sensitive data like voting results?
- What are some best practices for organizing and accessing data in multiple arrays in PHP?