Pulling Drop-down values from a database using Javascript and PHP

This tutorial will walk you through how to set drop-down boxes up to pull the values from a database as well as update the values of the other boxes based on what the user selects in the first and second boxes. This is handy if you are asking people to select categories of things they would like to search for, like tutorials. In this example we will be making a drop-down to select the group which will populate the category drop-down and then populate the sub-category drop-down based on which category is selected. We will be working with basic HTML, PHP, and MySQL as well as some basic JavaScript. To get started let’s set up our database. We will need to use three tables to achieve what we are doing. To start lets make our group table. The query to do so is following:

CREATE TABLE `group` (
  `id` int(10) NOT NULL auto_increment,
  `group` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

This will create a table called group and set it to have the fields below:

Id – unique primary key, integer, auto-increments
Group – name of the various groups (programming, networking, ect..)

It will also set the auto increment value to 10)because we are going to insert 9 records to the table and we will give them the ids.

INSERT INTO `group` VALUES(1, 'Programming');
INSERT INTO `group` VALUES(2, 'Graphic Design');
INSERT INTO `group` VALUES(3, 'Networking');
INSERT INTO `group` VALUES(4, 'Office Software');
INSERT INTO `group` VALUES(5, 'Operating Systems');
INSERT INTO `group` VALUES(6, 'Other');
INSERT INTO `group` VALUES(7, '3D and Video');
INSERT INTO `group` VALUES(8, 'Web Development');
INSERT INTO `group` VALUES(9, 'Databases');

These queries will create the groups that we will be using to populate our first drop-down. Now we need to create our category table.

CREATE TABLE `category` (
  `id` int(10) NOT NULL auto_increment,
  `group` varchar(100) NOT NULL default '',
  `category` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;

This will create a table called category with the following fields:

Id – unique primary key, integer, auto-increments
Group – name of the various groups from the previous drop-down (programming, networking, ect..)
Category – name of the categories that will be listed underneath the corresponding groups

This one also sets our auto-increment value for us so that when we insert the values next, we will start with the right number.

INSERT INTO `category` VALUES(1, 'Graphic Design', 'Fireworks');
INSERT INTO `category` VALUES(2, 'Graphic Design', 'Flash');
INSERT INTO `category` VALUES(3, '3D and Video', '3d Studio Max');
INSERT INTO `category` VALUES(4, '3D and Video', 'AutoCAD');
INSERT INTO `category` VALUES(5, 'Web Development', 'HTML and XHTML');
INSERT INTO `category` VALUES(6, 'Web Development', 'CSS');
INSERT INTO `category` VALUES(7, 'Web Development', 'Other');
INSERT INTO `category` VALUES(8, 'Programming', 'C and C++');
INSERT INTO `category` VALUES(9, 'Programming', 'Java');
INSERT INTO `category` VALUES(10, 'Databases', 'MySQL');
INSERT INTO `category` VALUES(11, 'Databases', 'Oracle');
INSERT INTO `category` VALUES(12, 'Operating Systems', 'Windows XP');
INSERT INTO `category` VALUES(13, 'Operating Systems', 'Linux');
INSERT INTO `category` VALUES(14, 'Operating Systems', 'Mac OS');
INSERT INTO `category` VALUES(15, 'Business Apps', 'Excel');
INSERT INTO `category` VALUES(16, 'Business Apps', 'Powerpoint');
INSERT INTO `category` VALUES(17, 'Business Apps', 'Word');
INSERT INTO `category` VALUES(18, 'Other', 'Tips and Tricks');
INSERT INTO `category` VALUES(19, 'Other', 'Other');
INSERT INTO `category` VALUES(20, 'Networking', 'TCP IP');
INSERT INTO `category` VALUES(21, 'Networking', 'Cisco');
INSERT INTO `category` VALUES(22, 'Office Software', 'Peachtree');
INSERT INTO `category` VALUES(23, 'Office Software', 'QuickBooks');

As, you can see we are inserting at least two values for each one so that we can see this thing in action. Now we need to create our sub-category table. This one will have several entries in it.

CREATE TABLE `subcategory` (
  `id` int(10) NOT NULL auto_increment,
  `category` varchar(100) NOT NULL default '',
  `subcategory` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT= 42;

This will create the following fields:

Id – unique primary key, integer, auto-increments
Category – name of the categories that will be listed underneath the corresponding groups that is related to those in the drop down.
Subcategory – The subcategories that belong to the corresponding category

Now we need to insert our data into this table:

INSERT INTO `subcategory` VALUES(1, 'Fireworks', 'Text Effects');
INSERT INTO `subcategory` VALUES(2, 'Fireworks', 'Other');
INSERT INTO `subcategory` VALUES(3, 'Flash', 'Animation');
INSERT INTO `subcategory` VALUES(4, 'Flash', 'Tweening');
INSERT INTO `subcategory` VALUES(5, '3d Studio Max', 'Animation');
INSERT INTO `subcategory` VALUES(6, '3d Studio Max', 'Effects');
INSERT INTO `subcategory` VALUES(7, 'AutoCAD', '3D');
INSERT INTO `subcategory` VALUES(8, 'AutoCAD', 'Architectural');
INSERT INTO `subcategory` VALUES(9, 'AutoCAD', 'Basics');
INSERT INTO `subcategory` VALUES(10, 'AutoCAD', 'Other');
INSERT INTO `subcategory` VALUES(11, 'CSS', 'General');
INSERT INTO `subcategory` VALUES(12, 'HTML and XHTML', '.htaccess');
INSERT INTO `subcategory` VALUES(13, 'HTML and XHTML', 'Advanced');
INSERT INTO `subcategory` VALUES(14, 'HTML and XHTML', 'Backgrounds');
INSERT INTO `subcategory` VALUES(15, 'Java', 'Applet Building');
INSERT INTO `subcategory` VALUES(16, 'Java', 'Application Building');
INSERT INTO `subcategory` VALUES(17, 'C and C++', 'Development');
INSERT INTO `subcategory` VALUES(18, 'C and C++', 'File Manipulation');
INSERT INTO `subcategory` VALUES(19, 'MySQL', 'General');
INSERT INTO `subcategory` VALUES(20, 'Oracle', 'General');
INSERT INTO `subcategory` VALUES(21, 'Linux', 'Administration');
INSERT INTO `subcategory` VALUES(22, 'Linux', 'Editing Files');
INSERT INTO `subcategory` VALUES(23, 'Windows XP', 'Administration');
INSERT INTO `subcategory` VALUES(24, 'Windows XP', 'Development');
INSERT INTO `subcategory` VALUES(25, 'Mac OS', 'General');
INSERT INTO `subcategory` VALUES(26, 'Mac OS', 'Networking');
INSERT INTO `subcategory` VALUES(27, 'Excel', 'General');
INSERT INTO `subcategory` VALUES(28, 'Powerpoint', 'General');
INSERT INTO `subcategory` VALUES(29, 'Word', 'General');
INSERT INTO `subcategory` VALUES(30, 'Networking', 'General');
INSERT INTO `subcategory` VALUES(31, 'Tips and Tricks', 'Hacks');
INSERT INTO `subcategory` VALUES(32, 'Tips and Tricks', 'OverClocking');
INSERT INTO `subcategory` VALUES(33, 'Other', 'BASH');
INSERT INTO `subcategory` VALUES(34, 'Other', 'MonitorTips');
INSERT INTO `subcategory` VALUES(35, 'TCP IP', 'General');
INSERT INTO `subcategory` VALUES(36, 'Cisco', 'Configuration');
INSERT INTO `subcategory` VALUES(37, 'Cisco', 'Programming');
INSERT INTO `subcategory` VALUES(38, 'Peachtree', 'Setup');
INSERT INTO `subcategory` VALUES(39, 'Peachtree', 'Configuration');
INSERT INTO `subcategory` VALUES(40, 'Quickbooks', 'Setup');
INSERT INTO `subcategory` VALUES(41, 'Quickbooks', 'Configuration');

Now our tables have been configured and we are ready to start writing the files to work with this database. First, we are going to write our connection string in separate file to allow for easy modification and also to be able to call the connection from any file by requiring it. Make a file and call it connection.php

<?php

$servername='localhost';
$dbusername='servername_dbname;
$dbpassword='password';
$dbname='database name;

connecttodb($servername,$dbname,$dbusername,$dbpassword);
function connecttodb($servername,$dbname,$dbuser,$dbpassword)
{
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());
}

?>

This simply sets the variable before running the connection string and allows the connection to carry to another file. Make sure you change you values in the first 4 declarations to the information needed to connect to your database. You can test the connection by going directly to that file. If you see nothing on the screen, the connection worked. If not, an error will show on the screen. This is the end of that file. Next we are going to create the html file that will actually display the form to the users – note that you could do this in the same file, but I felt for making it easy to understand, I would separate the files. I called this file index.html.

<html>
<head>
<title>Javascript Form Updater</title>
<script language="javascript" src="update.php"></script>
</head>

<body bgcolor="#ffffff" onload="fillCategory();">

<FORM name="drop_list" action="success.php" method="POST" >

<SELECT NAME="Main" onChange="SelectCat();" >
<Option value="">Main</option>
</SELECT>&nbsp;
<SELECT id="Category" NAME="Category" onChange="SelectSubCat();">
<Option value="">Category</option>
</SELECT>
<SELECT id="SubCat" NAME="SubCat">
<Option value="">SubCat</option>
</SELECT>
</form>

</body>

</html>

This simply create the form in HTML and tells it were to get the javascript, which is in update.php. Note that we do not have a button to submit, you will need to add that and gather your POST variables on another page which is ( in the tutorial) success.php. Now we need to make update.php

<?php

require "connection.php"; 
echo "

function fillCategory(){ 

";

This first section simply calls the connection file to establish the DB connection and then beings the Jscript function. Notice that we are using php to echo the function.

$q1=mysql_query("select * from `group`");
echo mysql_error();
while($nt1=mysql_fetch_array($q1)){
echo "addOption(document.drop_list.Main, '$nt1[group]', '$nt1[group]');";
}
?>
}

Next, we create the query that will bring back the original results for the first drop-down box. We setup a while statement to keep adding the option to the drop-down box until there are no more to add. This is run every time the file is initially loaded. We do this using a javascript function that we will declare at the bottom of the page.

function SelectCat(){

removeAllOptions(document.drop_list.Category);
addOption(document.drop_list.Category, "", "Category", "");

<?

Next, we create the next function. This function is run every time the group drop-down is changed.

$q2=mysql_query("select distinct(`group`) from category");

while($nt2=mysql_fetch_array($q2)){

echo "if(document.drop_list.Main.value == '$nt2[group]'){";
$q3=mysql_query("select category from category where `group`='$nt2[group]'");
while($nt3=mysql_fetch_array($q3)){
echo "addOption(document.drop_list.Category,'$nt3[category]', '$nt3[category]');";

} 
echo "}";
}
?>
}

This snippet selects each group from category only once (if it appears more than once, it will still only show it to me once). Then it checks to see if the value that it currently has is the value that is listed in the initial drop-down box. If it is, it runs a query on the category table to bring back all results that contains that group and adds them to the drop-down box for the categories.

function SelectSubCat(){

removeAllOptions(document.drop_list.SubCat);
addOption(document.drop_list.SubCat, "", "SubCat", "");

<?

$q4=mysql_query("select distinct(`category`) from subcategory");

while($nt4=mysql_fetch_array($q4)){

echo "if(document.drop_list.Category.value == '$nt4[category]'){";
$q5=mysql_query("select subcategory from subcategory where `category`='$nt4[category]'");
while($nt5=mysql_fetch_array($q5)){
echo "addOption(document.drop_list.SubCat,'$nt5[subcategory]', '$nt5[subcategory]');";

} 
echo "}";
}
?>
}

This section does the same thing the last two sections did but changing the variables a little bit to populate the third drop-down on selection of the second.

function removeAllOptions(selectbox)
{
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}


function addOption(selectbox, value, text )
{
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;

selectbox.options.add(optn);
}
[

Finally, we declare our two functions. The first one simply clears the drop-down boxes when it is called. The second one uses the JavaScript to add the option to the drop-down.
Now, if all three files are in the same directory you should be able to launch the html file and the first drop-down will be populated. Upon selection the second one will populate, and upon selection of that, the third one will. If it does not populate, go to the update.php file directly in your browser. You will get all the lines of JavaScript and you should see a PHP error on the page somewhere. You can use that error to trouble shoot your code. Please comment with questions and comments and thanks for reading.