This post was last updated on December 9th, 2023 at 06:58 am
Hi Dev,
Today, i we will show you select option subcategory by category in php. This article will give you simple example of select option subcategory by category in php. you will select option subcategory by category in php. In this article, we will implement a select option subcategory by category in php.
So let’s follow few step to create example of select option subcategory by category in php.
database.php
<?php $servername = "localhost"; $username = "root"; $password = ""; $db="example"; $conn = mysqli_connect($servername, $username, $password,$db); ?>
index.php
<?php include 'database.php'; $result = mysqli_query($conn,"SELECT * FROM category"); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Select Option Subcategory By Category In PHP - Codeplaners</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form> <div class="form-group"> <label >Category</label> <select class="form-control" id="category"> <option value="">Select Category</option> <?php while($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row["id"];?>"><?php echo $row["category_name"];?></option> <?php } ?> </select> </div> <div class="form-group"> <label for="sel1">Sub Category</label> <select class="form-control" id="sub_category"> </select> </div> </form> </div> <script> $(document).ready(function() { $('#category').on('change', function() { var category_id = this.value; $.ajax({ url: "get_subcat.php", type: "POST", data: { category_id: category_id }, cache: false, success: function(dataResult){ $("#sub_category").html(dataResult); } }); }); }); </script> </body> </html>
get_subcat.php
<?php include 'database.php'; $category_id=$_POST["category_id"]; $result = mysqli_query($conn,"SELECT * FROM category where category_id=$category_id"); ?> <option value="">Select SubCategory</option> <?php while($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row["id"];?>"><?php echo $row["subcategory_name"];?></option> <?php } ?>
I hope it will assist you…