Category Subcategory Dropdown in PHP + MySQL + Ajax

PHP + MySQL + Ajax category subcategory dropdown; Through this tutorial, i am going to show you how to create dynamic dependent category subcategory dropdown list in in PHP + MySQL + Ajax. And how to display subcategories by category in PHP + MySQL + Ajax.

Dynamic Category Subcategory Dropdown in PHP + MySQL + Ajax

  • Step 1 – Create PHP Project
  • Step 2 – Create Database Table And Connect App to DB
  • Step 3 – HTML Markup For Category & Subcategory Dropdown
  • Step 4 – Get Subcategory List By Category Id in PHP + MySQL

Step 1 – Create PHP Project

In step 1, Navigate to your local web server directory. And inside this directory, create one directory. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 2 – Create Database Table And Connect App to DB

In step 2, you need to create database and table. So run the following sql query to create database and table:

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;

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');

Then create a php file that named db.php. Which is used to connect phpmyadmin mysql database to project (demo).

So, now create db.php file and add the below given code into your file:

<?php

    $hName='localhost'; // host name

    $uName='root';   // database user name

    $password='';   // database password

    $dbName = "my_db"; // database name

    $conn= mysqli_connect($hName,$uName,$password,"$dbName");

      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
      }
?>

Step 3 – HTML Markup For Category & Subcategory Dropdown

In step 3, create a php file that named index.php. This file will display country state city dropdown list from MySQL database using jQuery Ajax. Now, you need to add the following html Markup code 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 - Laratutorials.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 - Laratutorials.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>

The following ajax code will fetch subcategories list and display in html markup dropdown by category id in PHP + MySQL + Ajax:

<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>

Step 4 – Get Subcategory List By Category Id in PHP + MySQL

In step 4, create one php file, which name fetch-subcategory-by-category.php. And add the following code into it:

<?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
}
?>

The fetch-subcategory-by-category.php file code will fetch all subcategories list in dropdown form data into MySQL database using PHP + AJAX.

Conclusion

PHP + MySQL + Ajax category subcategory dropdown; Through this tutorial,You have learned how to create dynamic dependent category subcategory dropdown list in in PHP + MySQL + Ajax. And how to display subcategories by category in PHP + MySQL + Ajax.

Recommended PHP Tutorials

Leave a Comment