tutorialswb

Saya adalah pendiri dari TutorialsWB.com dan TutorPHPID.com. Saya adalah Blogger dan Pengembang Web. Saya sudah ngeblog sejak 2016 dan mencari proyek online. Percayakan Pembuatan Website dan Aplikasi Anda kepada Kami.

Hubungi Saya

Membuat Multiple Select Dropdown Menggunakan PHP MySql dan Ajax


Apakah anda pernah menggunakan aplikasi android atau aplikasi berbasis web, biasanya untuk melengkapi profile seseorang, kalian harus memilih nama negara kemudian kemudian di arahkan untuk memilih provinsi dan kemudian kota.

Hal seperti di atas disebut multiple select dropdown menggunakan PHP Mysql. multiple select seperti ini banyak digunakan oleh para developer.

multi select dropdown using php


Langsung saja mari kita mulai dari awal, Pertama buat database dengan nama select kemudian masukkan struktur database dibawah ini.
 CREATE TABLE `cities` (
  `city_id` int(11) NOT NULL,
  `city` varchar(255) NOT NULL,
  `state_id` int(11) NOT NULL COMMENT 'state_id from the states table'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data untuk tabel `cities`
--

INSERT INTO `cities` (`city_id`, `city`, `state_id`) VALUES
(16, 'Grand Indonesia Mall', 7),
(17, 'Istiqlal Mosque', 7),
(18, 'Tanah Lot', 8);

-- --------------------------------------------------------

--
-- Struktur dari tabel `continents`
--

CREATE TABLE `continents` (
  `continent_id` int(11) NOT NULL,
  `continent` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data untuk tabel `continents`
--

INSERT INTO `continents` (`continent_id`, `continent`) VALUES
(1, 'Asia'),
(2, 'Australia');

-- --------------------------------------------------------

--
-- Struktur dari tabel `countries`
--

CREATE TABLE `countries` (
  `country_id` int(11) NOT NULL,
  `country` varchar(255) NOT NULL,
  `continent_id` int(11) NOT NULL COMMENT 'continent_id from the continents table'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data untuk tabel `countries`
--

INSERT INTO `countries` (`country_id`, `country`, `continent_id`) VALUES
(1, 'India', 1),
(2, 'Vietnam', 1),
(3, 'Indonesia', 1),
(4, 'Philippines', 1),
(5, 'Bhutan', 1),
(6, 'Maldives', 1),
(7, 'Hong Kong', 1),
(8, 'Australia', 2),
(9, 'New Zealand', 2),
(12, 'Papua New Guinea', 2);

-- --------------------------------------------------------

--
-- Struktur dari tabel `states`
--

CREATE TABLE `states` (
  `state_id` int(11) NOT NULL,
  `state` varchar(255) NOT NULL,
  `country_id` int(11) NOT NULL COMMENT 'country_id from the countries table'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data untuk tabel `states`
--

INSERT INTO `states` (`state_id`, `state`, `country_id`) VALUES
(7, 'Jakarta', 3),
(8, 'Bali', 3);

--
-- Indexes for dumped tables
--

--
-- Indeks untuk tabel `cities`
--
ALTER TABLE `cities`
  ADD PRIMARY KEY (`city_id`);

--
-- Indeks untuk tabel `continents`
--
ALTER TABLE `continents`
  ADD PRIMARY KEY (`continent_id`);

--
-- Indeks untuk tabel `countries`
--
ALTER TABLE `countries`
  ADD PRIMARY KEY (`country_id`);

--
-- Indeks untuk tabel `states`
--
ALTER TABLE `states`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT untuk tabel yang dibuang
--

--
-- AUTO_INCREMENT untuk tabel `cities`
--
ALTER TABLE `cities`
  MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52;

--
-- AUTO_INCREMENT untuk tabel `continents`
--
ALTER TABLE `continents`
  MODIFY `continent_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

--
-- AUTO_INCREMENT untuk tabel `countries`
--
ALTER TABLE `countries`
  MODIFY `country_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=24;

--
-- AUTO_INCREMENT untuk tabel `states`
--
ALTER TABLE `states`
  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=53;
COMMIT; 

Kedua buat file dengan nama db.php kemudian masukkan struktur database dibawah ini.
 <?php
define('HOSTNAME','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME', 'select');

//global $con;
$con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
// Check connection
if(mysqli_connect_errno($con)) echo "Failed to connect MySQL: " .mysqli_connect_error();
?>
 

Berikutnya buat file dengan nama js.js file ini dibuat menggunakan ajax
 $(document).ready(function() {


 //Change in continent dropdown list will trigger this function and
 //generate dropdown options for county dropdown
 $(document).on('change','#continent', function() {
  var continent_id = $(this).val();
  if(continent_id != "") {
   $.ajax({
    url:"get_data.php",
    type:'POST',
    data:{continent_id:continent_id},
    success:function(response) {
     //var resp = $.trim(response);
     if(response != '') {
      $("#country").removeAttr('disabled','disabled').html(response);
      $("#state").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
     } else {
      $("#country, #state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
     }
    }
   });
  } else {
   $("#country, #state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  }
 });


 //Change in coutry dropdown list will trigger this function and
 //generate dropdown options for state dropdown
 $(document).on('change','#country', function() {
  var country_id = $(this).val();
  if(country_id != "") {
   $.ajax({
    url:"get_data.php",
    type:'POST',
    data:{country_id:country_id},
    success:function(response) {
     //var resp = $.trim(response);
     if(response != '') $("#state").removeAttr('disabled','disabled').html(response);
     else $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
    }
   });
  } else {
   $("#state, #city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  }
 });



 //Change in state dropdown list will trigger this function and
 //generate dropdown options for city dropdown
 $(document).on('change','#state', function() {
  var state_id = $(this).val();
  if(state_id != "") {
   $.ajax({
    url:"get_data.php",
    type:'POST',
    data:{state_id:state_id},
    success:function(response) {
     if(response != '') $("#city").removeAttr('disabled','disabled').html(response);
     else $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
    }
   });
  } else {
   $("#city").attr('disabled','disabled').html("<option value=''>------- Select --------</option>");
  }
 });


});
 

Buat file dengan nama index.php file ini sebagai form. Masukkan sourch code berikut
 
<!DOCTYPE html>
<html>
<head>
 <title>Multiple Select</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

 <script type="text/javascript" src="js.js"></script>
 <script type="text/javascript" src="jquery.min.js"></script>

</head>
<body>
 <?php include('db.php'); ?>
 <br /><br />
 <div class="container">
  <nav class="navbar navbar-inverse">
   <div class="container-fluid">
    <div class="navbar-header">
     <a class="navbar-brand" href="https://www.tutorialswb.com/">Home</a>
     <a class="navbar-brand" href="index.php">Multiple Select</a>
    </div>
   </div>
  </nav>
  <br />
  <h2 align="center">Multiple Select Menggunakan PHP MySql</h2>
  <br />


  <div class="form-group">
   <label for="exampleSelect1" class="control-label">Select Continent</label>&nbsp;&nbsp;&nbsp;&nbsp;<font color=red>Required (*)</color></font>
   <div class="controls">
    <select name="continent" class="form-control" id="continent">
     <option value=''>------- Select --------</option>
     <?php 
     $sql = "select * from `continents`";
     $res = mysqli_query($con, $sql);
     if(mysqli_num_rows($res) > 0) {
      while($row = mysqli_fetch_object($res)) {
       echo "<option value='".$row->continent_id."'>".$row->continent."</option>";
      }
     }
     ?>
    </select>
   </div>
  </div>

  <div class="form-group">
   <label for="exampleSelect2" class="control-label">Select Country</label>&nbsp;&nbsp;&nbsp;&nbsp;<font color=red>Required (*)</color></font>
   <div class="controls">
    <select name="country" class="form-control" id="country" disabled="disabled"><option>------- Select --------</option></select>
   </div>
  </div>

  <div class="form-group">
   <label for="exampleSelect3" class="control-label">Select Provincy</label>&nbsp;&nbsp;&nbsp;&nbsp;<font color=red>Required (*)</color></font>
   <div class="controls">
    <select name="state" class="form-control" id="state" disabled="disabled"><option>------- Select --------</option></select>
   </div>
  </div>

  <div class="form-group">
   <label for="exampleSelect4" class="control-label">Select City</label>&nbsp;&nbsp;&nbsp;&nbsp;<font color=red>Required (*)</color></font>
   <div class="controls">
    <select name="city" class="form-control" id="city" disabled="disabled"><option>------- Select --------</option></select>
   </div>
  </div>

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

Terakhir buat file dengan nama get_data.php file ini berfungsi memanggil data kemudian memasukkan kedalam fiel index.php
 <?php include('db.php');?>

<?php

if (isset($_POST['continent_id'])) {
 
 $qry = "select * from countries where continent_id=".mysqli_real_escape_string($con,$_POST['continent_id'])." order by country";
 $res = mysqli_query($con, $qry);
 if(mysqli_num_rows($res) > 0) {
  echo '<option value="">------- Select -------</option>';
  while($row = mysqli_fetch_object($res)) {
   echo '<option value="'.$row->country_id.'">'.$row->country.'</option>';
  }
 } else {
  echo '<option value="">No Record</option>';
 }

} else if(isset($_POST['country_id'])) {

 $qry = "select * from states where country_id=".mysqli_real_escape_string($con,$_POST['country_id'])." order by state";
 $res = mysqli_query($con, $qry);
 if(mysqli_num_rows($res) > 0) {
  echo '<option value="">------- Select -------</option>';
  while($row = mysqli_fetch_object($res)) {
   echo '<option value="'.$row->state_id.'">'.$row->state.'</option>';
  }
 } else {
  echo '<option value="">No Record</option>';
 }

} else if(isset($_POST['state_id'])) {

 $qry = "select * from cities where state_id=".mysqli_real_escape_string($con,$_POST['state_id'])." order by city";
 $res = mysqli_query($con, $qry);
 if(mysqli_num_rows($res) > 0) {
  echo '<option value="">------- Select -------</option>';
  while($row = mysqli_fetch_object($res)) {
   echo '<option value="'.$row->city_id.'">'.$row->city.'</option>';
  }
 } else {
  echo '<option value="">No Record</option>';
 }
}

?> 

Kalian bisa mendownlaod filenya langsung dibawah ini, silahkan kembangkan dan gunakan sesuai kebutuhan aplikasi anda.


Sekian share kali ini semoga apa yang kami share bermanfaat bagi anda, jangan lupa share dan tinggalkan komentar dibawah dan mulai berdiskusi dengan kami.



Baca Juga