How to chain more than 1 dropdown boxes to MySQL

Im using Mysql for my database but how do i include more than 1 chained dropdown boxes to this coding because my sql tables also includes things such as statement and location other than commodity.By the way this coding is actually taken from this forum and edited but i cant seem to find any solution in including more than one chained dropdown boxes. Im sorry because i am still new to php and mysql.

<?php
/*
* Testing configuration
*/
define('ENVIR',0);
define('ENVIR_DEV',0);
define('ENVIR_LIVE',1);

/*
* Data base credentials (replace this with your db credentials)
*/
define('DB_USER','root');
define('DB_PWD','Password');
define('DB_HOST','localhost');
define('DB_NAME','database');

/*
* Connect to database
*/
try {
	$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PWD);
} catch(PDOExeption $e) {

	if(ENVIR == ENVIR_DEV) {
		echo '<p>',$e->getMessage(),'</p>';
	}

	echo '<p>Unable to connect to database<p>';
	exit;
}

/*
* Template variables
*/
$tpl = array(
	'filter'=>array(
		 '#action'		=> $_SERVER['SCRIPT_NAME']
		,'#method'  	=> 'get'
		,'commodity'	=> array(
			'#values'=>array(
				 array('value'=>'','label'=>'All')
			)
		)
	)
	,'grid'=>array(
		'commodity'=>array()
	)
);

/*
* Populate form filter last name options
*/
$stmt = $db->query('SELECT Commodity FROM my30_rsl GROUP BY Commodity ORDER BY Commodity ASC');

if($stmt === false) {
	echo '<p>Unable to populate required data to build page.</p>';
	exit;
}

while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
	$tpl['filter']['commodity']['#values'][] = array(
		 'label'		=> $row['Commodity']
		,'value'		=> $row['Commodity']
		,'selected'		=> isset($_GET['filter'],$_GET['filter']['commodity']) && $_GET['filter']['commodity'] == $row['Commodity']
	);
}


/*
* Populate user grid
*/
$stmt = $db->prepare(sprintf(
	'SELECT Commodity,SupplierName FROM my30_rsl %s'
	, isset($_GET['filter'],$_GET['filter']['commodity']) && !empty($_GET['filter']['commodity'])?'WHERE Commodity = :commodity1':''
));

if($stmt === false) {
	echo '<p>Unable to populate required data to build page.</p>';
	exit;
}

$stmt->execute(isset($_GET['filter'],$_GET['filter']['commodity']) && !empty($_GET['filter']['commodity'])?array(':commodity1'=>$_GET['filter']['commodity']):array());

while($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
	$tpl['grid']['commodity'][] = $row;
}

/*
* Start template output
*/
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
	<title>Supplier Dictionary</title>
</head>
<body>

<!-- user filter template -->
<form action="<?php echo $tpl['filter']['#action']; ?>" method="<?php echo $tpl['filter']['#method']; ?>">
	<fieldset>
		<legend>Filters</legend>
		<ul>
			<li>
				<label for="filter-commodity">Commodity</label>
				<select name="filter[commodity]" id="filter-commodity">
					<?php 
					foreach($tpl['filter']['commodity']['#values'] as &$option) {
						printf(
							'<option value="%s"%s>%s</option>'
							,htmlentities($option['value'])
							,$option['selected']?' selected':''
							,htmlentities($option['label'])
						);
					} 
					?>
				</select>
			</li>
			<li>
				<input type="submit" name="filter[submit]" value="Filter Commodity"> 
			</li>
		</ul>
	</fieldset>
</form>

<!-- data grid template -->
<table>
	<caption>Supplier Dictionary</caption>
	<thead>
		<tr>
			<th>Supplier</th>
			<th>Commodity</th>
		</tr>
	</thead>
	<tbody>
		<?php
			if(!empty($tpl['grid']['commodity'])) {
				foreach($tpl['grid']['commodity'] as &$name) {
					printf(
						'<tr>
							<td>%s</td>
							<td>%s</td>
						 </tr>'
						 ,htmlentities($name['SupplierName'])
						 ,htmlentities($name['Commodity'])
					);
				}
			} else {
				echo '<tr><td colspan="2">No commodity available</td></tr>';
			}
		?>
	</tbody>
</table>

</body>
</html>

Can you explain in a bit more detail what you are actually trying to achieve with a “chained dropdown”? Do you mean that you want, say, a second dropdown which will be populated when the user chooses a value in the first dropdown?

If that’s the case, I think you’ll need to do it with Ajax, and have a bit of code that triggers when the user selected from the first dropdown. That will then retrieve all the options based on their first selection.

If you mean something else, can you explain in more detail please?

what i actually wanted was having multiple dropdown box based on the categories form mysql table to filter the mysql query
example:

|supplier name | location | commodity| status | (these are the categories in my table)
-------------------------------------------------
|company A     |france    | PCB      |good    |
|companyB      |thailand  |Mounting  |bad     |

I am finding a way for it to filter these categories and and display the data. From the coding I have posted, I was able to to it with only one category, it is possible to include more categories to filter the data ?

Sry for the unclear explanation

Well, the short answer is “yes”. If you want to display multiple drop-downs all at the same time, with the content the same regardless of the selection in any of the other drop-downs, then it’s much easier - simply repeat the code you already have (well, maybe simplify it a bit) for each of the drop-down categories. Enclose them all within the single <form> tag so that they are all processed by your form handler.

You seem to be using a template system in the code, which is not something I am familiar with, so the exact method and variable names and so on may well have some additional role to play. But basically it will be a case of repeating the first query (the one that builds $tpl['filter']['commodity']['#values'][]) to build the other drop-downs, and then modifying the second query (which on quick glance it appears is the one building the “results”) to take into account which other filters have been selected.

1 Like

thank you for the explanation =)

but I have another question if I want to take into account the other dropdown selection for the filtering process what is the proper way to code it ? Using AJAX ?

It doesn’t need to be using Ajax, as your current code doesn’t seem to use that.

The section of code that starts with the comment “Populate user grid” is the bit that actually executes the query based on your filter selection, and sticks the results in the array $tpl['grid']['commodity'], so it would be a case of expanding that code to deal with the additional filter conditions.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.