Dynamic Dependent Dropdown using PHP and MySQLi

Hi-ya Technoz, In this tutorial we are going to learn Dynamic Dependent Dropdown or sometimes you may also called it relational select boxes. In this case we going to implement using procedural PHP and off course MySQLi. Sometimes we need to create select boxes which must dependent on each other. For example, If first select box contain countries then it will decide which state will be in the next select box. Similarly, After selecting the state select box it will decide which cities in the next dropdown.

1. Create Database for Dynamic Dependent Dropdown

To store the Relational select boxes values a table need to create in the database. So lets create the database by using following queries. The following SQL  creates category table which consist of  id, category_name,category_link, parent_id  and sort_order details.

Dumping data for table `category to make relational select boxes

Now, lets fill some records into the table ‘category’

 

2. Database Configuration

First, to make it convenient, we will create a new PHP file for database configuration named dbconfig.php  that holds all configured parameters:

3. Code for Dynamic Dependent Dropdown

In this script we have added two Dynamic Dependent Dropdown one for parent category and another for child category. In the first Select box we select the values from database those are having parent_id=0.

JavaScript’s onChange ()  function use to get the selected dropdown’s value when users change the selection of drop down.

When user selects a value from first dropdown then onchange function gets called and based on selection value we display value for second drop down.

Based on the selection on the second dynamic dependent dropdown we print the information related to selection value.

Following code shows dynamic dependent dropdown using procedural PHP and MySQLi.

4. CSS for the Relational Select Boxes

Add styling to the Dynamic Dependent  by using CSS to make the content pretty and save the file by name dependentdropdown.css

Now place the two files in the same folder. Remember to save the files with the right extensions (respectively “.htm” and “.css”) . The combined view of the both HTML and CSS is illustrate in the following image.

Dynamic Dependent Dropdown PHP and MySQLi/Relational Select boxes

Finally You have Learned to create Cascaded Select boxes by using procedural PHP and MySQLi.

If you have any doubts regarding to this tutorial feel free to ask in the comment section below.

To catch even more knowledgeable and easy understandable tutorials please subscribe to get email notification.

Download Source Code

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.