Click here to Skip to main content
15,918,516 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am trying to populate a dropdownlist based on another dropdownlist selection and not getting the result. Bellow is my code, Please tell me where I am wrong.

The Controller: index.php
PHP
	$link = mysqli_connect('localhost', 'root', 'aweklin@topnetconsulting');
	if (!$link){
		echo 'There was an error connecting to database server: ' . mysqli_error($link);
		exit();
	}
	if (!mysqli_select_db($link, 'practice')){
		echo 'There was an error selecting practice database: ' . mysqli_error($link);
		exit();
	}
	
	$sql = "SELECT cat_id, category FROM category ORDER BY category";
	$result = mysqli_query($link, $sql);
	
	if (!$result){
		echo 'There was an error fetching categories: ' . mysqli_error($link);
		exit();
	}
	
	while ($row = mysqli_fetch_array($result)){
		$categories[] = array('catid' => $row['cat_id'], 'cat' => $row['category']);
	}
	
	if (isset($_REQUEST['catDDL'])){
		$catid = $_REQUEST['catDDL'];
		$sql = "SELECT subcat_id, subcategory FROM category WHERE cat_id = '$catid' ORDER BY category";
		$result = mysqli_query($link, $sql);
		
		if (!$result){
			echo 'There was an error fetching subcategories: ' . mysqli_error($link);
			exit();
		}
		
		while ($row = mysqli_fetch_array($result)){
			$subcategories[] = array('catid' => $row['subcat_id'], 'cat' => $row['subcategory']);
		}
	}
	
	include 'test.html.php';
?>


The Form: text.html.php
<pre lang="PHP"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
	<title>Categories</title>
	<script type="text/javascript">
		function populateSubCategory(){
			window.location = 'index.php';
		}
	</script>
</head>

<body>

	<form id="catform" action="index.php" method="post">
		Category:	
		<select id="catDDL" name="catDDL"  önchange="populateSubCategory();">
			<option value="">Select One<option
			<?php if(isset($categories)): ?><br mode="hold" /?>				<?php foreach($categories as $category): ??>
					<option value="<?php echo $category['catid']; ?>"?>
						<?php echo $category['cat']; ??>		
					</option>
				<?php endforeach; ??>
			<?php endif; ??>
		</select>
		<br />
		Sub Category:
		<select id="subCatDDL" name="subCatDDL">
			<option value="">Select sub category</option>
			<?php if(isset($subcategories)): ??>
				<?php foreach($subcategories as $subcategory): ??>
					<option value="<?php echo $subcategory['catid']; ?>"?>
						<?php echo $subcategory['cat']; ??>		
					</option>
				<?php endforeach; ??>
			<?php endif; ??>
		</select>
	</form>
	
</body>
</html>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900