Dynamic Dependent Select Box in PHP

15

The dynamic dependent select box is mostly used for country state city dropdown. In this tutorial, we’ll implement relational dropdown of country state city using jQuery, Ajax, PHP and MySQL. Means state is related with country and city is related with the state. Based on changing of country & state, respective state & city will be fetched from the database without reloading the page using jQuery, Ajax, PHP and MySQL.

At first, the country dropdown would be displayed with all countries. When a country would be chosen, the respective states would be fetched from the MySQL database and appear in the states dropdown. Alike when a state would be chosen, the respective cities will be fetched from the MySQL database and appear in the cities dropdown.

Database & Tables

Create a database, like location_db. location_db consists of three tables countries, states, and cities. states table has a relation with countries table and cities table has a relation with states table.

countries Table:
This table contains all the countries data. countries table SQL would like below.

states Table:
This table contains all the states data and country_id FOREIGN KEY. states table SQL would like below.

cities Table:
This table contains all the cities data and state_id FOREIGN KEY. cities table SQL would like below.

dbConfig.php File

This file helps to connect and select the database.

index.php File

This file contains a jQuery library, JavaScript, HTML and PHP code.

The following JavaScript code is used for getting the state and city data from ajaxData.php file using ajax. Also, it displays the returned HTML of the ajaxData.php file to the respective select box.

Using PHP & HTML the initial country select box is displayed along with the state and city select box.

ajaxData.php File

This file is requested by the Ajax and in this file state or city data is fetched from the database based on the requested country_id or state_id. Also, the respective select options HTML are returned to the Ajax success function.

 

Leave A Reply

Your email address will not be published.