mahadi_mohammad mahadi_mohammad - 1 year ago 136
MySQL Question

Dependent dropdown list in PHP from same table of the database

I need to make some dpendent dropdown lists. Here, from first dropdown list, whenever I select Region, in second dropdown list's option, it should show corresponding Country of the selected Region. But after selecting a Region, second dropdown list doesn't show anything. I searched for solution, but didn't find appropriate one as I'm doing all this for only one table of database.

Database


SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

CREATE TABLE `geo` (
`Region` varchar(200) NOT NULL,
`Country` varchar(200) NOT NULL,
`City` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `geo` (`Region`, `Country`, `City`) VALUES
('Asia', 'Bangladesh', 'Dhaka'),
('Europe', 'France', 'Paris'),
('Asia', 'Bangladesh', 'Khulna'),
('Europe', 'France', 'Avignon'),
('Europe', 'Spain', 'Barcelona'),
('Europe', 'Spain', 'Madrid'),
('Asia', 'Srilanka', 'Colombo');


dbconnect,php

<?php
error_reporting( ~E_DEPRECATED & ~E_NOTICE );

define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
define('DBNAME', 'ddl');

$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);

if ( !$conn ) {
die("Connection failed : " . mysql_error());
}

if ( !$dbcon ) {
die("Database Connection failed : " . mysql_error());
}

?>


index.php

<?php
require_once 'dbconnect.php';

$query ="SELECT * FROM geo";
$results = mysql_query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>DDL - Select</title>
</head><?php
$bul[10000007] = false;
?>

<style>
body{width:610px;}
.frmDronpDown {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px 0px;padding:40px;}
.demoInputBox {padding: 10px;border: #F0F0F0 1px solid;border-radius: 4px;background-color: #FFF;width: 50%;}
.row{padding-bottom:15px;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getCountry(val) {
$.ajax({
type: "POST",
url: "get_country.php",
data:'region_id='+val,

success: function(data){
$("#country-list").html(data);
}
});
}

function selectRegion(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>

<body>
<div class="frmDronpDown">
<div class="row">

<form>
<label>Region: </label>
<select name="region" id="region-list" class="demoInputBox" onChange="getCountry(this.value);">
<option value="">Select Region</option>

<?php

$sql = "SELECT * FROM geo";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {

if($bul[$row['Region']] != true && $row['Region'] != 'Region'){
?>
<option value="<?php echo $row['Region']; ?>"><?php echo $row['Region']; ?></option>
<?php
$bul[$row['Region']] = true;
}
}
?>

</select>
</div>


<div class="row">
<label>Country: </label>
<select name="country" id="country-list" class="demoInputBox">
<option value="">Select Country</option>
</select>


</form>

</div>
</div>

</body>
</html>


get_country.php

<?php
require_once 'dbconnect.php';


if(!empty($_REQUEST["region_id"])) {

$query ="SELECT * FROM geo WHERE Region =" . $_POST["region_id"];
$result = mysql_query($query);
?>
<option value="">Select Country</option>

<?php
while($row2=mysql_fetch_assoc($result)){
if($bul2[$row2['Country']] != true && $row2['Country'] != 'Country') { ?>
<option value="<?php echo $row['Country']; ?>"><?php echo $row['Country']; ?> </option>
<?php
$bul2[$row2['Country']] = true;
}
}
}
?>

Answer Source

Use mysqli functions instead of mysql functions. And also use mysqli_escape_string() function to prevent sql injection.

In get_country.php file you missed ' before and after $_POST["region_id"]

$query ="SELECT * FROM geo WHERE Region =" . "'" . mysqli_escape_string( $_POST["region_id"] ) ."'";

And also you need fix in $row['Country'], it would be $row2['Country'].

Here is working codes on my mechine:

index.php

<?php
require_once 'dbconnect.php';
$query   = "SELECT * FROM geo";
$results = mysqli_query($conn, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>DDL - Select</title>
</head><?php
$bul[10000007] = false;
?>

<style>
body{width:610px;}
.frmDronpDown {border: 1px solid #F0F0F0;background-color:#C8EEFD;margin: 2px       0px;padding:40px;}
.demoInputBox {padding: 10px;border: #F0F0F0 1px solid;border-radius:  4px;background-color: #FFF;width: 50%;}
.row{padding-bottom:15px;}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"   type="text/javascript"></script>
<script>
function getCountry(val) {
$.ajax({
    type: "POST",
    url: "get_country.php",
    data:'region_id='+val,

   success: function(data){
    $("#country-list").html(data);
  }
  });
  }

  function selectRegion(val) {
  $("#search-box").val(val); 
  $("#suggesstion-box").hide();
  }
  </script>

 <body>
<div class="frmDronpDown">
<div class="row">

<form>
<label>Region: </label>
<select name="region" id="region-list" class="demoInputBox"      onChange="getCountry(this.value);">
    <option value="">Select Region</option>

        <?php
$sql = "SELECT * FROM geo";
$res = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($res)) {
    if ($bul[$row['Region']] != true && $row['Region'] != 'Region') {
?>
               <option value="<?php
        echo $row['Region'];
?>"><?php
        echo $row['Region'];
?></option>
        <?php
        $bul[$row['Region']] = true;
    }
}
?>

    </select>
</div>

<div class="row">
    <label>Country: </label>
    <select name="country" id="country-list" class="demoInputBox">
        <option value="">Select Country</option>
    </select>   

</form>
</div>
</div>
</body>
</html>

get_country.php

<?php
    require_once 'dbconnect.php';


    if(!empty($_REQUEST["region_id"])) {

    $query ="SELECT * FROM geo WHERE Region =" . "'" . mysqli_escape_string($conn, $_POST["region_id"] ) ."'";
    //echo $query ="SELECT * FROM geo WHERE Region =" . "'" . $_POST["region_id"] ."'";

    $result = mysqli_query($conn, $query);
?>
    <option value="">Select Country</option>

<?php
    while($row2=mysqli_fetch_assoc($result)){

        //var_dump($row2);
        if($bul2[$row2['Country']] != true && $row2['Country'] != 'Country' || 1)        { ?>
            <option value="<?php echo $row2['Country']; ?>"><?php echo     $row2['Country']; ?>  </option>
 <?php  
         $bul2[$row2['Country']] = true;
         }
     }
    }
?>

and dbconnect.php

<?php
error_reporting( ~E_DEPRECATED & ~E_NOTICE );

define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
define('DBNAME', 'ddl');

$conn = mysqli_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysqli_select_db($conn, DBNAME);

if ( !$conn ) {
    die("Connection failed : " . mysqli_error());
}

if ( !$dbcon ) {
    die("Database Connection failed : " . mysqli_error());
}

?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download