How to Create a Dynamic Dropdown Menu using PHP/MySQLi and Bootstrap 4
Submitted by nurhodelta_17 on Friday, April 6, 2018 - 23:51.
Getting Started
First, we need the jQuery library and Bootstrap 4. I've included these files in the downloadable of this tutorial but if you want, you can download them yourself using the links below: For jQuery For Bootstrap 4 Note: Bootstrap JS depends on jQuery to work. Therefore you need to declare jQuery first before declaring boostrap js.Creating our Database
Next, we create the database that we are going to filter in this tutorial. I've included a SQL file in the downloadable of this tutorial. All you have to do is import the said file. If you have no idea on how to import, please visit my tutorial How import .sql file to restore MySQL database. You should be able to create a database named test.Displaying our Nav
Lastly, we display our nav with the dynamic dropdown list from our database. Create a new file, name it as index.php and paste the codes below.- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>How to Create a Dynamic Dropdown Menu using PHP/MySQLi and Bootstrap 4</title>
- <link rel="stylesheet" type="text/css" href="bootstrap4/css/bootstrap.min.css">
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-light bg-light">
- <a class="navbar-brand" href="#">SourceCodeSter</a>
- <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
- <span class="navbar-toggler-icon"></span>
- </button>
- <div class="collapse navbar-collapse" id="navbarSupportedContent">
- <ul class="navbar-nav mr-auto">
- <li class="nav-item dropdown">
- <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
- Category
- </a>
- <div class="dropdown-menu" aria-labelledby="navbarDropdown">
- <?php
- //connection
- $conn = new mysqli('localhost', 'root', '', 'test');
- $sql = "SELECT * FROM categories";
- $query = $conn->query($sql);
- while($row = $query->fetch_assoc()){
- echo "
- <a class='dropdown-item' href='#'>".$row['name']."</a>
- ";
- }
- ?>
- </div>
- </li>
- </ul>
- </div>
- </nav>
- <script src="jquery.min.js"></script>
- <script src="bootstrap4/js/bootstrap.min.js"></script>
- </body>
- </html>
Add new comment
- 3464 views