Search code examples
htmlbootstrap-4php-7

How to build bootstrap 4 multi level dropdown navbar on hover using php pdo?


I am trying to integrate nested categories to bootstrap navbar with dropdown. I Have tried many different examples and did searches on google but none solved my problem. My structured tree is showing dropdowns when I click on them nothing hapening. which should show subcategories in dropdown.

You can see in image

https://ibb.co/kMhV2QQ

After many tries and code changes this is what I have:

function dynamic_menu($parent_array, $sub_array, $qs_val = "menu", $main_id = "nav", $sub_id = "subnav", $extra_style = "foldout") {
    $menu = "<ul id=\"".$main_id."\" class=\"navbar-nav mr-auto\">\n";
    foreach ($parent_array as $pkey => $pval) {
        if (!empty($pval['count'])) {
            $menu .= "<li class=\"nav-item\"><a href=\"#\" class=\"nav-link dropdown-toggle\" id=\"navbarDropdownMenuLink-333\" data-toggle=\"dropdown\"
          aria-haspopup=\"true\" aria-expanded=\"false\">".$pval['label']."</a>\n";
        } else {
            $menu .= "<li class=\"nav-item dropdown\"><a class=\"nav-link\" href=\"".$pval['link']."\">".$pval['label']."</a></li>\n";
        }
        if (!empty($_REQUEST[$qs_val])) {
            $menu .= "<div class=\"dropdown-menu dropdown-default\" aria-labelledby=\"navbarDropdownMenuLink-333\" id=\"".$sub_id."\">\n";
            foreach ($sub_array as $sval) {
                if ($pkey == $_REQUEST[$qs_val] && $pkey == $sval['parent']) {
                    $menu .= "<a class=\"dropdown-item\" href=\"".rebuild_link($sval['link'], $qs_val, $sval['parent'])."\" target=\"_blank\">".$sval['label']."</a>\n";
                }
            }
            $menu .= "</div>\n";
            $menu .= "</li>\n";
        }
    }
    $menu .= "</ul>\n";
    return $menu;
}

Here is the navbar I am tryign to integrate:

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  
<!--Navbar -->
<nav class="mb-1 navbar navbar-expand-lg navbar-dark bg-info">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent-333"
    aria-controls="navbarSupportedContent-333" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarSupportedContent-333">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home
          <span class="sr-only">(current)</span>
        </a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" id="navbarDropdownMenuLink-333" data-toggle="dropdown"
          aria-haspopup="true" aria-expanded="false">Dropdown
        </a>
        <div class="dropdown-menu dropdown-default" aria-labelledby="navbarDropdownMenuLink-333">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>
  </div>
</nav>
<!--/.Navbar -->

Here is my sql structure if needed:

    CREATE TABLE IF NOT EXISTS `dyn_menu` (
  `id` int(11) NOT NULL auto_increment,
  `label` varchar(50) NOT NULL default '',
  `link_url` varchar(100) NOT NULL default '#',
  `parent_id` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

Solution

  • Here is the best solition I found for my question after many searches and trying many different examples and I think this is the best way to have a bootstrap navbar work properly.

    its a Multi-level Bootstrap Menu on hover with jquery

    And codes:

    function bootstrap_menu($pdo, $parent_id, $level = null) {
    //First query to find category id 
            $stmt = $pdo->prepare("SELECT * FROM categories WHERE parent_id =:parent_id");
            $stmt->bindParam(":parent_id", $parent_id, PDO::PARAM_INT);
            $stmt->execute();
    //FetchAll as $row to use
            foreach ($stmt->fetchAll() as $row) {
        //Second query to find cildren of main categories
            $sql = $pdo->prepare("SELECT count(*) FROM categories WHERE parent_id =:cat_id");
            $sql->bindParam(":cat_id", $row['cat_id'], PDO::PARAM_INT);
            $sql->execute();
        //Here we check for parent and level valuess 
            if($sql->fetchAll()[0][0] !== '0' && $level !== 0){ 
        //Here we check if category has children if so display dropdown
                echo "<li class=\"nav-item dropdown\">\n";
                echo "<a class=\"nav-link dropdown-toggle\" href=\"".htmlspecialchars($row['seo_url'])."\" id=\"navbarDropdown\" role=\"button\" data-toggle=\"dropdown\"
                        aria-haspopup=\"true\" aria-expanded=\"false\">\n";
                echo $row['cat_name'];
                echo "</a>\n";
                echo "<ul class=\"dropdown-menu\" aria-labelledby=\"navbarDropdown\">\n";
                bootstrap_menu($pdo, $row[0], $level - 1);
                echo "</ul>\n";
                echo "</li>\n";
            }elseif($level == 0){
        //Here we set our actice class $my_class
                $my_class= htmlspecialchars($row['cat_name']);          
                if($my_class== 'Home'){
                    echo "<li class=\"nav-item active\">\n";
                    echo "<a href=\"".htmlspecialchars($row['seo_url'])."\" class=\"nav-link \">\n";
                    echo htmlspecialchars($row['cat_name']);
                    echo "</a>\n";
                    echo "</li>\n";
                }else{
                    echo "<li class=\"nav-item\">\n";
                    echo "<a href=\"".htmlspecialchars($row['seo_url'])."\" class=\"nav-link\">\n";
                    echo htmlspecialchars($row['cat_name']);
                    echo "</a>\n";
                    echo "</li>\n";
                }
            }
            else { 
                echo "<li class=\"dropdown-item\">";
                echo "<a href=\"".htmlspecialchars($row['seo_url'])."\" class=\"dropdown-item\">\n";
                echo htmlspecialchars($row['cat_name']);
                echo "</a>\n";
                echo "</li>\n";
            }
            unset($sql);
        }
    unset($stmt);
    }