Is it recommended to use database queries to retrieve page names and IDs for breadcrumb navigation in PHP?
When implementing breadcrumb navigation in PHP, it is recommended to use database queries to retrieve page names and IDs for each level of the breadcrumb. This allows for dynamic generation of breadcrumbs based on the current page's hierarchy in the database. By querying the database for the parent pages of the current page, you can construct the breadcrumb trail accurately.
// Assuming you have a database connection established
// Get the current page's ID
$current_page_id = $_GET['page_id'];
// Query the database to retrieve the current page's name
$current_page_query = "SELECT page_name FROM pages WHERE page_id = $current_page_id";
$current_page_result = mysqli_query($connection, $current_page_query);
$current_page = mysqli_fetch_assoc($current_page_result);
// Query the database to retrieve the parent pages of the current page
$breadcrumbs = array();
$parent_id = $current_page_id;
while ($parent_id != 0) {
$parent_page_query = "SELECT page_id, page_name FROM pages WHERE page_id = $parent_id";
$parent_page_result = mysqli_query($connection, $parent_page_query);
$parent_page = mysqli_fetch_assoc($parent_page_result);
array_unshift($breadcrumbs, $parent_page);
$parent_id = $parent_page['parent_id'];
}
// Output the breadcrumb trail
foreach ($breadcrumbs as $crumb) {
echo '<a href="page.php?page_id=' . $crumb['page_id'] . '">' . $crumb['page_name'] . '</a> > ';
}
echo $current_page['page_name'];