Ajax country, state, city dropdown using php & mysql

First you need to create database with three table as country, state and city. state table has relation with country table and city table has relation with state table.

Country State City tabel

CREATE TABLE `country` (
`country_id` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`country_name` VARCHAR( 25 ) NOT NULL
) ENGINE = MYISAM ;

CREATE TABLE `state` (
`state_id` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`country_id` INT( 3 ) NOT NULL ,
`state_name` VARCHAR( 35 ) NOT NULL
) ENGINE = MYISAM ;

CREATE TABLE `city` (
`city_id` INT( 3 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`state_id` INT( 3 ) NOT NULL ,
`city_name` VARCHAR( 35 ) NOT NULL
) ENGINE = MYISAM ;

Above are the three table the we use in this tutorials each table have three columns which are dependent to each other.

 Dbconfig.Php

  • Simple Database Configuration file.
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
	$e->getMessage();
}

 Index.Php

  • main index file where three dropdown box are available
  • Dynamic Dependent Select Box using jQuery and PHP
  1. setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch(PDOException $e)
    {
    	$e->getMessage();
    }

    Country : --Select Country-- prepare("SELECT * FROM country"); $stmt->execute(); while($row=$stmt->fetch(PDO::FETCH_ASSOC)) { ?>

  2. Dynamic Dependent Select Box using jQuery and PHP

get_state.php

  • This file is for get the all the state record from the state tabel and load dynamically.
prepare("SELECT * FROM state WHERE country_id=:id");
	$stmt->execute(array(':id' => $id));
	?>

Select State :fetch(PDO::FETCH_ASSOC)) { ?>

get_city.php

prepare("SELECT * FROM city WHERE state_id=:id");
	$stmt->execute(array(':id' => $id));
	?>

Select City : fetch(PDO::FETCH_ASSOC)) { ?>

  • all the main file are displayed remaining css and java script file include normally we do. It’s not big thing.
  • Depending on the dropdown ajax call the function and query should run and get the data from database and populate in dropdown list.
  • Loding image is indicate loding time of ajax function. When Query  response comes then login image invisible.

Let's Think together, Say Something !