Facebooktwittergoogle_plusredditpinterestlinkedinmail


In this tutorial, we are going to learn how to change the district dropdown list option based on the selected state name using PHP-PDO.

In this example, we have two dropdowns for listing states and districts. On changing states drop-down values, the corresponding district dropdown values will be loaded dynamically using jQuery AJAX.

File structure for this tutorial

config.php — Database connection file.

index.php — Main file having drop down

get_district.php — used to retrieve the district based on the selected state name.

MySQL Database structure for this tutorial

In this tutorial two MySQL Database table is used.

state table structure

CREATE TABLE `state` (
  `StCode` int(11) NOT NULL,
  `StateName` varchar(150) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

district table structure

CREATE TABLE `district` (
  `DistCode` int(11) NOT NULL,
  `StCode` int(11) DEFAULT NULL,
  `DistrictName` varchar(200) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Step 1: Create a database connection file (config.php)

<?php 
// DB credentials.
error_reporting(0);
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','demos');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
?>

Step2: Create a HTML form with two fields . One is for state and another one is for district.

<form name="insert" action="" method="post">
  <table width="100%" height="117"  border="0">
  <tr>
    <th width="27%" height="63" scope="row">Sate :</th>
    <td width="73%"><select onChange="getdistrict(this.value);"  name="state" id="state" class="form-control" >
<option value="">Select</option>
<!--- Fetching States--->
<?php
$sql="SELECT * FROM state";
$stmt=$dbh->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while($row =$stmt->fetch()) { 
  ?>
<option value="<?php echo $row['StCode'];?>"><?php echo $row['StateName'];?></option>
<?php }?>
</select></td>
  </tr>
  <tr>
    <th scope="row">District :</th>
    <td><select name="district" id="district-list" class="form-control">
<option value="">Select</option>
</select></td>
  </tr>
</table>

</form>

Step3: Getting States using jQuery AJAX

This script contains a function that will be called on changing state dropdown values. It will send AJAX request to a PHP page to get corresponding district dropdown options.

<script>
function getdistrict(val) {
$.ajax({
type: "POST",
url: "get_district.php",
data:'state_id='+val,
success: function(data){
$("#district-list").html(data);
}
});
}
</script>

Step 4: Read the district table using PHP based on the selected state name.

This PHP code connects the database to retrieve district table values based on the state id passed by jQuery AJAX call.

<?php
require_once("config.php");
if(!empty($_POST["state_id"])) 
{
$stateid=$_POST["state_id"];
$sql=$dbh->prepare("SELECT * FROM district WHERE StCode=:stateid");
$sql->execute(array(':stateid' => $stateid));	
?>
<option value="">Select District</option>
<?php
while($row =$sql->fetch())
{
?>
<option value="<?php echo $row["DistrictName"]; ?>"><?php echo $row["DistrictName"]; ?></option>
<?php
}
}
?>

How to run this script

1.Download the zip file

2.Extract the file and copy statedistdropdown-pdo folder

3.Paste inside root directory(for xampp xampp/htdocs, for wamp wamp/www, for lamp var/www/html)

4.Open PHPMyAdmin (http://localhost/phpmyadmin)

5.Create a database with name demos

6.Import regdb.sql file(given inside the zip package )

7.Run the script http://localhost/statedistdropdown-pdo

Download Full source Code (jQuery Dependent Dropdown List – States and Districts Using PHP- PDO)

Size: 33.7 KB

Version: V 1.0