In this tutorial, we will show you how to create dynamic category and subcategory tree dropdowns using PHP MySQL Ajax.
In this guide, we will populate the subcategories in the dropdown list based on the category value selected in the dropdown.
This dynamic category and subcategory dropdown list in PHP MySQL using ajax will look like:
Dynamic Category and Subcategory Dependent Dropdown List in PHP, MySQL and Ajax
Here are steps to create category and subcategory dropdown:
Step 1: Create Table
First of all, open your database and run the following sql query to create a categories table in database:
CREATE TABLE `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `parent_id` int(11) NOT NULL DEFAULT '0', `category` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Step 2: Insert Data In Table(Category and SubCategory)
In this step, run the following sql query to insert category and subcategory into mysql database in php:
INSERT INTO `categories` (`id`, `parent_id`, `category`) VALUES (1, 0, 'General'), (2, 0, 'PHP'), (3, 0, 'HTML'), (4, 3, 'Tables'), (5, 2, 'Functions'), (6, 2, 'Variables'), (7, 3, 'Forms');
Step 3: Create DB Connection PHP File
In this step, create a file name db.php and update the following code into db.php file:
<?php $servername='localhost'; $username='root'; $password=''; $dbname = "my_db"; $conn=mysqli_connect($servername,$username,$password,"$dbname"); if(!$conn){ die('Could not Connect MySql Server:' .mysql_error()); } ?>
Note that, This code is used to create a MySQL database connection in PHP project.
Step 4: Create Form to Category, SubCategory Dropdown in Form
In this step, create an index.php file and update the below PHP and HTML code into index.php file.
Now, update the following php mysql ajax and html form into index.php file:
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Dynamic Dropdown Category Subcategory List in PHP MySQL using ajax - Tutsmake.COM</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet"> <!-- Styles --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" > <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Nunito', sans-serif; font-weight: 200; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 13px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <h2 class="text-primary">Dynamic Dropdown Category Subcategory List in PHP MySQL using ajax - Tutsmake.COM</h2> </div> <div class="card-body"> <form> <div class="form-group"> <label for="CATEGORY-DROPDOWN">Category</label> <select class="form-control" id="category-dropdown"> <option value="">Select Category</option> <?php require_once "db.php"; $result = mysqli_query($conn,"SELECT * FROM categories where parent_id = 0"); while($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row['id'];?>"><?php echo $row["category"];?></option> <?php } ?> </select> </div> <div class="form-group"> <label for="SUBCATEGORY">Sub Category</label> <select class="form-control" id="sub-category-dropdown"> </select> </div> </form> </div> </div> </div> </div> </div> <script> $(document).ready(function() { $('#category-dropdown').on('change', function() { var category_id = this.value; $.ajax({ url: "fetch-subcategory-by-category.php", type: "POST", data: { category_id: category_id }, cache: false, success: function(result){ $("#sub-category-dropdown").html(result); } }); }); }); </script> </body> </html>
Note that, This HTML code shows the category and subcategory dropdown list. And the PHP and ajax code of this file will dynamic populating subcategories in dropdown list based on the selected category in dropdown.
Step 5: Get SubCategory in Dropdown List by Category Id
Now, create a new php file named fetch-subcategory-by-category.php.
So update the following php and html code into fetch-subcategory-by-category.php file:
<?php require_once "db.php"; $category_id = $_POST["category_id"]; $result = mysqli_query($conn,"SELECT * FROM categories where parent_id = $category_id"); ?> <option value="">Select SubCategory</option> <?php while($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row["id"];?>"><?php echo $row["category"];?></option> <?php } ?>
This file code will fetch and show a subcategory (second dropdown) based on selected category (previous dropdown selection) in PHP.
Conclusion
In this tutorial, you have learned how to dynamic populating subcategories in dropdown list based on the selected category in PHP MySQL using ajax.
Thank you for this code. Its working! But…how can I edit and update it using ajax. Any help would be highly appreciated. Thank you
Thanks for the code, i need this!
mysql or mysqli?