Saturday, December 28, 2024
Google search engine
HomeLanguagesCategory Subcategory Dropdown in PHP MySQL Ajax

Category Subcategory Dropdown in PHP MySQL Ajax

Dynamic category and subcategory tree dropdown list in PHP MySQL ajax. In this tutorial, we will show you how to dynamic populate categories and subcategories in the dropdown tree using PHP MySQL Ajax or How to create categories and subcategories in PHP MySQL using ajax.

Sometimes, you need to create separate tables for displaying selected subcategories based on selected category dropdowns. But in this tutorial, we will use only a single table (category and subcategory in one table) for a PHP dynamic populate dropdown list onchange of category and subcategories.

This tutorial will help you step by step on how to implement a dynamic category and subcategory dropdown list onchange in PHP MySQL using Ajax or populate the second dropdown based on the first PHP. As well as learn, how to fetch data from the database in the dropdown list in PHP using jQuery ajax.

In this PHP ajax MySQL get categories and subcategories example, we will show subcategory in the dropdown list based on selected category value in PHP using ajax from the database.

This dynamic category and subcategory dropdown list in PHP MySQL using ajax will look like:

category subcategory dropdown list in php mysql ajax

Dynamic Category and Sub Category Dependent Dropdown List in PHP + MySQL using Ajax

Follow the below simple and easy and retrieve and display category and subcategory tree in dropdown list onchange in PHP MySQL using jQuery ajax:

  • Step 1: Create Table
  • Step 2: Insert Data In Table(Category and SubCategory)
  • Step 3: Create DB Connection PHP File
  • Step 4: Create Form And Category, SubCategory Dropdown in Form
  • Step 5: Get Sub Category in Dropdown List by Category Id

Step 1: Create Table

First of all, open your database and run the following sql query to create categories table into 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.

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.

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>

Step 5: Get SubCategory in Dropdown List by Category Id

Now, create a new php file named fetch-subcategory-by-category.php. This file code will fetch and show a subcategory (second dropdown) based on selected category (previous dropdown selection) in 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
}
?>

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.

RELATED ARTICLES

Most Popular

Recent Comments