o.danielcoker o.danielcoker - 22 days ago 7
PHP Question

Display Categories and Subcategories in Dropdown Menu

Am trying to display categories and subcategories in a dropdown menu and I have this:

<?php


$cat_query = "SELECT * FROM `categories`";
$select_categories = mysqli_query($connection, $cat_query);
while ($cat = mysqli_fetch_array($select_categories)) {

$cat_id = $cat['cat_id'];
$cat_title = $cat['cat_title'];

echo "<li>";
echo "<a href='#'>$cat_title <span class='caret'></span></a>";

$sub_query = "SELECT * FROM `sub_categories` WHERE `cat_id` = $cat_id";
$select_sub_categories = mysqli_query($connection, $sub_query);

while ($sub = mysqli_fetch_array($select_sub_categories)) {

$subcat_id = $sub['subcat_id'];
$subcat_title = $sub['subcat_title'];
echo "<ul class='dropdown-menu'><li>";
echo "<a href='#'>$subcat_title</a></li>";
echo "</ul>";
}

echo "</li>";

}

?>


It is actually fetching the categories from the database but it's not displaying correctly.

On the desktop version it displays like this:
Desktop View

On the mobile version it displays like this:
Mobile View

Am I doing anything wrong?
Any help will be appreciated.
Thanks

Answer

Since you did not provide the css,javascript or some html code , I assume the problem is in this php block

while ($sub = mysqli_fetch_array($select_sub_categories)) {

              $subcat_id = $sub['subcat_id'];
              $subcat_title = $sub['subcat_title'];
              echo "<ul class='dropdown-menu'><li>";
              echo "<a href='#'>$subcat_title</a></li>";
              echo "</ul>";
            }

From this code block it seems like you are creating a list of drop down menu , so maybe it should be

echo "<ul class='dropdown-menu'>";
while ($sub = mysqli_fetch_array($select_sub_categories)) {

              $subcat_id = $sub['subcat_id'];
              $subcat_title = $sub['subcat_title'];
              echo "<li><a href='#'>$subcat_title</a></li>";
 }
echo "</ul>";

If this does not work You should check your javascript,css,html code again. Because I don't know your design plan