Ask Question

Menu


Need a Website Or Web Application Or Any Help In Code As Per Your Budget, Contact Us: +91 9437911966 (Whatsapp)

Show subcategory by select category PHP


dbcontroller.php

<?php
class DBController {
	private $host = "localhost";
	private $user = "root";
	private $password = "";
	private $database = "student";
	private $conn;
	
	function __construct() {
		$this->conn = $this->connectDB();
	}
	
	function connectDB() {
		$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
		return $conn;
	}
	
	function runQuery($query) {
		$result = mysqli_query($this->conn,$query);
		while($row=mysqli_fetch_assoc($result)) {
			$resultset[] = $row;
		}		
		if(!empty($resultset))
			return $resultset;
	}
	
	function numRows($query) {
		$result  = mysqli_query($this->conn,$query);
		$rowcount = mysqli_num_rows($result);
		return $rowcount;	
	}
}
?>

get_subcategory.php

<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["category_id"])) {
	$query ="SELECT * FROM subcategory WHERE category_id = '" . $_POST["category_id"] . "'";
	$results = $db_handle->runQuery($query);
?>
	<option value="">Select subcategory</option>
<?php
	foreach($results as $subcategory) {
?>
	<option value="<?php echo $subcategory["id"]; ?>"><?php echo $subcategory["name"]; ?></option>
<?php
	}
}
?>

index.php

 <?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$query ="SELECT * FROM category";
$results = $db_handle->runQuery($query);
 
?>
<html>
<head>
<title> Show subcategory by select category PHP</title>
<head>
<style>
body{width:500px;
}
.container {background-color:orange;
margin: 2px 0px;
padding:40px;
}
.demoInputBox {
padding: 10px;
width: 50%;}
.row{
	padding-bottom:20px;
	}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getSubcategory(val) {
	$.ajax({
	type: "POST",
	url: "get_subcategory.php",
	data:'category_id='+val,
	success: function(data){
		$("#subcategory-list").html(data);
	}
	});
}

function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<center>
<div class="container">
<div class="row">
<label>Category:</label><br/>
<select name="category" id="country-list" class="demoInputBox" onChange="getSubcategory(this.value);">
<option value="">Select Category</option>
<?php
foreach($results as $category) {
?>
<option value="<?php echo $category["id"]; ?>"><?php echo $category["category_name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<label>Subcategory:</label><br/>
<select name="state" id="subcategory-list" class="demoInputBox">
<option value="">Select Subcategory</option>
</select>
</div>
</div>
</center>
</body>
</html>


Buy Server in very low Price