Create dynamic select country state and city

Create dynamic select country state and city

Creating a dynamic country, state and city dropdown in web development is important to enhance the user experience, especially for forms that require location details. This guide provides a complete solution using PHP, jQuery, and MySQL, allowing users to select each dropdown based on their preferences. We’ll start by setting up our database structure, building the HTML form, and adding the necessary JavaScript to enable dynamic state and city populations based on the user’s country and state selection.

Create Database

To begin, let’s create three tables in our MySQL database:

  1. countries: Stores country names.
  2. states: Stores states with a foreign key referencing the countries table.
  3. cities: Stores cities with a foreign key referencing the states table.

Here’s a SQL script to create and populate the database:

				
					CREATE DATABASE countrystatecity;
USE countrystatecity;

-- Table for countries
CREATE TABLE `countries` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `countries` (`name`) VALUES ('India'), ('Nepal');

-- Table for states
CREATE TABLE `states` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `country_id` INT NOT NULL,
  `name` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`country_id`) REFERENCES `countries`(`id`)
);

INSERT INTO `states` (`country_id`, `name`) VALUES 
(1, 'Delhi'), 
(1, 'Uttar Pradesh'), 
(2, 'Madhesh'), 
(2, 'Bagmati');

-- Table for cities
CREATE TABLE `cities` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `state_id` INT NOT NULL,
  `name` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`state_id`) REFERENCES `states`(`id`)
);

INSERT INTO `cities` (`state_id`, `name`) VALUES 
(1, 'New Delhi'), 
(2, 'Lucknow'), 
(3, 'Birgunj'), 
(4, 'Kathmandu');
				
			

Create database connection in php

Create a conn.php file to handle the database connection:

				
					<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "countrystatecity";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
				
			

Creating Country, State and City Dropdown Form

The HTML form will have three dropdowns for country, state and city. When a country is selected, it triggers an AJAX call to fetch the corresponding states. Similarly, selecting a state triggers an AJAX call to fetch the corresponding cities.

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Country, State, City Dropdown</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        select {
            width: 100%;
            height: 45px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-5">
                <form>
                    <label for="country">Country:</label>
                    <select id="country" name="country">
                        <option value="">Select Country</option>
                        <?php
                        include './conn.php';
                        $result = $conn->query("SELECT * FROM countries");
                        while ($row = $result->fetch_assoc()) {
                            echo "<option value='{$row['id']}'>{$row['name']}</option>";
                        }
                        ?>
                    </select>
                    <br><br>
                    <label for="state">State:</label>
                    <select id="state" name="state">
                        <option value="">Select State</option>
                    </select>
                    <br><br>
                    <label for="city">City:</label>
                    <select id="city" name="city">
                        <option value="">Select City</option>
                    </select>
                </form>
            </div>
        </div>
    </div>
    
</body>
</html>
				
			
				
					<script>
        $('#country').change(function() {
            var countryID = $(this).val();
            if (countryID) {
                $.ajax({
                    type: "POST",
                    url: "getStates.php",
                    data: {country_id: countryID},
                    success: function(html) {
                        $('#state').html(html);
                        $('#city').html('<option value="">Select City</option>');
                    }
                });
            } else {
                $('#state').html('<option value="">Select State</option>');
                $('#city').html('<option value="">Select City</option>');
            }
        });

        $('#state').change(function() {
            var stateID = $(this).val();
            if (stateID) {
                $.ajax({
                    type: "POST",
                    url: "getCities.php",
                    data: {state_id: stateID},
                    success: function(html) {
                        $('#city').html(html);
                    }
                });
            } else {
                $('#city').html('<option value="">Select City</option>');
            }
        });
    </script>
				
			

Backend logic for state and city retrieval

Create two PHP files—getStates.php and getCities.php—to retrieve states and cities respectively based on the selected country or state.

getStates.php

				
					<?php
include 'conn.php';
if (isset($_POST['country_id'])) {
    $country_id = $_POST['country_id'];
    $result = $conn->query("SELECT * FROM states WHERE country_id = $country_id");
    echo '<option value="">Select State</option>';
    while ($row = $result->fetch_assoc()) {
        echo "<option value='{$row['id']}'>{$row['name']}</option>";
    }
}
?>
				
			

getCities.php

				
					<?php
include 'conn.php';
if (isset($_POST['state_id'])) {
    $state_id = $_POST['state_id'];
    $result = $conn->query("SELECT * FROM cities WHERE state_id = $state_id");
    echo '<option value="">Select City</option>';
    while ($row = $result->fetch_assoc()) {
        echo "<option value='{$row['id']}'>{$row['name']}</option>";
    }
}
?>
				
			

Conclusion

Their tutorial provides a step-by-step guide to creating a dynamic country-state-city dropdown using PHP, jQuery, and MySQL. By implementing this feature, you increase the usability and interactivity of your web forms, making it easier for users to select relevant geographic data.

Select country, state and city dropdown source code

FREE DOWNLOAD

Send download link to:

coding2w_newspaper

Leave a Reply

Your email address will not be published. Required fields are marked *