The dynamic dependent select box is used to auto-populate the dependent data in the dropdown list. Based on the drop-down selection, the dependent data are retrieved from the database and displayed in the next select box. Generally, the dynamic dependent select box is used to implement Country State City dependent dropdown functionality. You can easily implement dynamic dependent dropdown without page refresh using Ajax in PHP.
Dynamic dependent dropdown is very useful to fetch dynamic relational data from the database and listed in multiple select boxes. In this tutorial, we will show you how to implement a relational dropdown of country state city using jQuery, Ajax, PHP, and MySQL. In the dependent select box, the state is related to the country, and the city is related to the state. Based on changing of country, the respective state & city is fetched from the database without reloading the page using jQuery, Ajax, PHP, and MySQL.
In this example script, we will integrate country, state, and city dependent dropdown select boxes with PHP and MySQL.
Before getting started to build a dynamic dependent dropdown list with PHP and MySQL, take a look at the file structure.
dynamic_dependent_dropdown_with_php/ ├── dbConfig.php ├── index.php ├── ajaxData.php └── js/ └── jquery.min.js
To store the data of the country, state, and city, three tables are required in the database. Also, there would be a relationship between countries, states, and cities table. The states table has a relation with the countries table and the cities table has a relation with the states table.
The following SQL creates a countries
table in the MySQL database.
CREATE TABLE `countries` (
`country_id` int(11) NOT NULL AUTO_INCREMENT,
`country_name` varchar(50) CHARACTER SET utf8 NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following SQL creates a states
table with parent country_id
field in the MySQL database.
CREATE TABLE `states` (
`state_id` int(11) NOT NULL AUTO_INCREMENT,
`country_id` int(11) NOT NULL,
`state_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following SQL creates a cities
table with parent state_id
field in the MySQL database.
CREATE TABLE `cities` (
`city_id` int(11) NOT NULL AUTO_INCREMENT,
`state_id` int(11) NOT NULL,
`city_name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The dbConfig.php file is used to connect the database using PHP and MySQL. Specify the database host ($dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per your database credentials.
<?php
// Database configuration
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";
// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
HTML & PHP Code:
Initially, all the country data is fetched from the database and listed in the country dropdown. Once a value is selected in the country dropdown, the respective data is listed in the state and city dropdown.
<?php
// Include the database config file
include_once 'dbConfig.php';
// Fetch all the country data
$query = "SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC";
$result = $db->query($query);
?>
<!-- Country dropdown -->
<select id="country">
<option value="">Select Country</option>
<?php
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<!-- State dropdown -->
<select id="state">
<option value="">Select country first</option>
</select>
<!-- City dropdown -->
<select id="city">
<option value="">Select state first</option>
</select>
JavaScript Code:
Once a country is selected, the dependent states are fetched from the server-side script (ajaxData.php
) using jQuery and Ajax. Likewise, by selecting the state, the dependent cities are retrieved from the server-side script (ajaxData.php
) using jQuery and Ajax.
Include the jQuery library first, it is required to initiate Ajax requests.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
Initiate Ajax request to fetch the dependent data (state and city) from the database without page refresh using jQuery.
<script>
$(document).ready(function(){
$('#country').on('change', function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change', function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
The ajaxData.php is called by the Ajax request to retrieve the dependent data from the database using PHP and MySQL. The state and city dropdown HTML is returned to the success method of the Ajax request.
country_id
is provided,
state_id
is provided,
<?php
// Include the database config file
include_once 'dbConfig.php';
if(!empty($_POST["country_id"])){
// Fetch state data based on the specific country
$query = "SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC";
$result = $db->query($query);
// Generate HTML of state options list
if($result->num_rows > 0){
echo '<option value="">Select State</option>';
while($row = $result->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif(!empty($_POST["state_id"])){
// Fetch city data based on the specific state
$query = "SELECT * FROM cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC";
$result = $db->query($query);
// Generate HTML of city options list
if($result->num_rows > 0){
echo '<option value="">Select city</option>';
while($row = $result->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
After the form submission, you can get the value of the dynamic dependent select boxes using PHP. Use the $_POST method to retrieve the selected option value in PHP.
HTML Code:
<form action="" method="post">
<!-- Country dropdown -->
<select id="country" name="country">
<option value="">Select Country</option>
</select>
<!-- State dropdown -->
<select id="state" name="state">
<option value="">Select state</option>
</select>
<!-- City dropdown -->
<select id="city" name="city">
<option value="">Select city</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
PHP Code:
<?php
if(isset($_POST['submit'])){
echo 'Selected Country ID: '.$_POST['country'];
echo 'Selected State ID: '.$_POST['state'];
echo 'Selected City ID: '.$_POST['city'];
}
?>
Multi-select Dropdown List with Checkbox using jQuery
The dynamic dependent select boxes are a very useful element when you want to allow the user to select values from the multiple dropdown list. In the example code, we have shown the dynamic dependent select boxes for country state city dropdown in PHP. You can easily extend the dynamic dependent select boxes functionality and implement Ajax country state city dropdown with PHP and MySQL. If you have a large number of data, use the JSON data type in Ajax and PHP for a fast response.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thanks for your great tutorial.
The question is: When i choose one of the many cities,
I want to push a button and the selected city_id, return to index.php.
i want all city if state = 0 Please help
I am going to use the code for a create page. The data will be added to database. If I have a page to edit the data, how do I edit the code to do the edit?
Thank you for this code. But how do we insert the value into the database instead of the ID value?
To insert the value (name) in the database, use the following.
thank u vry muc for this code…its successfully working
I want put the values that were upload in data base and show in the selcts to modify
thank you, this is very very helpful, but I wonder how to insert the actual value into the database to another table because when i try to insert it, the value becomes number. I hoping for a tutorial for this.
How can we insert the Country, State, and City Name into the databases instead of the ID?
how to update the country state city
when submitting to the database is submitted as id ,is it possible that its insert into database by its name not as ID. Please share the code
Possible to get single value depends on selection using THIS code ?
thank your for giving me ta logic really very helpful
I was looking up a method to wrap a PHP code that provided a functionality for users to subscribe to a tag into a button. For example, when a user clicks a subscribe button on a tag page, that tag is added to the user’s database. What I have achieved so far is a successful code to subscribe, however, instead of activating that code on clicking a button, it self-executes every time the user visits a tag page. How can I limit the code execution to a button? I was directed to this blog via StackExchange. Apparently, it is possible to do that via an Ajax call.
Excellent
Output submitted as id ,is it possible that its insert into database by its name not as ID,by using Submit button
Hi, Thanks for your great tutorial. Is it possible to reload the page after every change in select box ?
Place the following line of code in
success
event. It will reload the current page on the success of Ajax request.manyyyyy manyyyy thanks to you for this code .
It is possible index.php and ajaxData.php are combined in one file? if it possible how abou URL in the javascript at the index.php?
wow, this saves me a lot of time! this is awesome! thank you!
sir have you any crud operation in php oop with ajax plz send me on my email address if u have i need urgent
@Nabeel We’ve already published the CRUD operations using Ajax in PHP, see this tutorial from here – http://www.codexworld.com/php-crud-operations-jquery-ajax-mysql/
Hello, great functionality I’ been search for something like that for a long time ago.
I’d like to experiment this on WordPress, I’ve tried to retrieve data from tables on WordPress database with same prefix, but only the select countries is populated, is there anyone here can explain a good way to do this work ?
Appreciate and thank you in advance. (sorry for my bad English 😛 )
i need help here guys, i want to use those options list to be a criteria for another search in mysql tables, if you choose two option and you click in submit button you will get another result based on what you have choose.
Thank you so much!
Thank you so much for the code. But how to pass multiple values to ajax for example multiple country values like india and australia ad pass it to ajax??
@Manoj You can pass the multiple values in
data
, same like the following example.I have got it.
Thanks fr this example
State dropdown becomes empty because first Success function returns an undefined object after selecting country.
‘data’ value is set correctly based on selection.
$(‘#state’).html(html); – This statement gives out the undefined object. It is not fetching State values from database. Any idea of why is it returning undefined object?
PS: I am using this example for other case. I have other fields which replaces Country,State,City.
hi,
thank you for this code first, i want to store name in php mysql table i don’t want to store id how to store name help me please.
thank you
I already fix another box select, thank you!!
how to add another box select under city?
how can we insert the Country, State, and City Name into the databases instead of the ID?
very nice code sir.. but i try to pass the values to another table assuming i am doing a registration system. what goes into the table is the ID and not the country/state/city itself. any idea how to turn this arond
Thanks for the script
How to pass the selected country id value together with state id ???
@Sergiu You can get the selected Country ID using the below code.
Now pass the Country ID through ajax.
thanks for this tutorial, it was really helpful
Thank you very much sir, this is very useful for my capstone project 🙂
Thank you Very Much 🙂
Thanks dear
much informative
thank you for posting it.
Thanks very much, works with 5…
Sir,
Is it possible to add further drop down like villages etc after city ?
Also I wants to display using echo the dropdown fields on results.
Please email me the solution
Thanks very much, but please how can we insert the Country, State, and City Name into the databases instead of the ID?