[RESOLVED] Dependent select boxes with PHP & MySQL
Hello all,
I want to do something that seems very simple but it's a bit hard to explain, so I'll just give you an example.
Suppose you have a MySQL database with 2 tables -
Cars (id, name)
Models (id, name, car_id)
The models include a reference to the car they belong to. For example, if the table "Cars" has 2 rows - (1,Mercedes) and (2,Volkswagen), then an example for a model that belongs to Mercedes in the "Models" table would be (1,E-Class,1), the latter 1 being the id of Mercedes.
My problem is this: I want to have 2 select boxes, one representing the car and the other representing the model. But, the point is that when the user changes his car selection, the other select box changes automatically so as to include only models that belong to the selected car.
I hope you understood this annoying explanation :-)
For people who may look for that in the future, here's my PHP implementation of that code (using the database I explained in the first message):
PHP Code:
<?
$mysql_link = mysql_connect(DBHOST,DBUSER,DBPASS) or die ("can't connect to mysql");
$mysql_select = mysql_select_db(DBNAME,$mysql_link) or die ("can't select db");
?>
<html>
<head>
<title>Dynamic Dropdown</title>
<script language="javascript">
function setOptions(chosen) {
var selbox = document.myform.selectmodel;
selbox.options.length = 0;
if (chosen == "0") {
selbox.options[selbox.options.length] = new Option('First select a car','0');
}
<?
$car_result = mysql_query("SELECT * FROM cars") or die(mysql_error());
while(@($c=mysql_fetch_array($car_result)))
{
?>
if (chosen == "<?=$c['id'];?>") {
Thank you so much.
I have used your drop down menu for awhile, and it works great. However, I have encounter another problem. when I query subcategory from my database which I already selected. I cannot display the full list in the database.
Here is a picture, you see only the selected subcategory showed, but not everything on the listed. dropdown.png
Here is another picture of the full list of subcategory dropdown2.png
I wonder do you have any idea how you solve this problem?
For people who may look for that in the future, here's my PHP implementation of that code (using the database I explained in the first message):
PHP Code:
<?
$mysql_link = mysql_connect(DBHOST,DBUSER,DBPASS) or die ("can't connect to mysql");
$mysql_select = mysql_select_db(DBNAME,$mysql_link) or die ("can't select db");
?>
<html>
<head>
<title>Dynamic Dropdown</title>
<script language="javascript">
function setOptions(chosen) {
var selbox = document.myform.selectmodel;
selbox.options.length = 0;
if (chosen == "0") {
selbox.options[selbox.options.length] = new Option('First select a car','0');
}
<?
$car_result = mysql_query("SELECT * FROM cars") or die(mysql_error());
while(@($c=mysql_fetch_array($car_result)))
{
?>
if (chosen == "<?=$c['id'];?>") {
Bookmarks