I'm trying to build a navigation bar using pages stocked in a database. Nothing difficult for the first level but it gets trickier when pages have to be listed as children of a same parent. here's my code :
$dropdown = array();
while ($pages = mysqli_fetch_assoc($rq_page)) {
$url_pg = url_rewrite('page-' . $pages["id"] . '-' . $pages["intitule"] . '');
// Creating a dropdown button
if($pages["dropdown"] == "oui" && $pages["parent"] == 0) {
echo '<li class="nav-item dropdown">';
echo '<a class="nav-link dropdown-toggle" data-toggle="dropdown" id="Preview" href="#" role="button" aria-haspopup="true" aria-expanded="false">';
echo $pages["intitule"];
echo '</a>';
echo '<div class="dropdown-menu" aria-labelledby="Preview">';
foreach($dropdown as $variable) {
echo '<a class="dropdown-item" href="#">' . $variable . '</a>';
}
echo '</div>';
echo '</li>';
}
// If single page = no dropdown
else if($pages["dropdown"] == "non" && $pages["parent"] == 0) {
echo '<li class="nav-item">';
echo '<a class="nav-link" href="' . $url_pg . '">' . $pages["intitule"] . '</a>';
echo '</li>';
}
// If content is a dropdown item
else {
$dropdown[] = '"' . $pages["parent"] . '" => "' . $pages["intitule"] . '"';
}
}
So. First I get the databse content. Then I create an array() to list every content that has a $pages["parent"] equals the mother's ID. The while() deals with the 3 types of content : single page, dropdown page and items of the dropdown button.
i tried many PHP methods. The first level appears properly but the $dropdown array remains empty when used into the while() loop. When printed outside of the while(), it show the content I passed through the else { }
Can you see something wrong in this code and what would be the best way to create the navigation ? Let me know if I can provide more information. Thanks for your help.
Your code doesn't work because when it finds a page that has $pages["dropdown"] == "oui"
, the $dropdown
array is always empty.
The reason why it's always empty is because your query returns dropdown "item" pages last, after all of the dropdown "button" pages. If you add var_dump($dropdown)
into a few strategic places in the loop you'll see it for yourself.
A quick hacky fix is changing the ordering of your query, so that the dropdown "items" (with parent>0) are returned first:
SELECT id, intitule, parent, dropdown FROM db_page ORDER BY parent DESC
This will make every dropdown "button" include every dropdown "item," including the ones that are not related. The sort order will need further modifications to make your current approach work the way you expect.