PHP SQL依赖下拉列表

时间:2019-01-26 18:27:27

标签: php jquery mysql ajax

我正在尝试创建一组动态的从属下拉列表。在第三个列表中进行选择时,我想填充两个列表。即,当选择Select1时,Select2和Select3同时自动填充。我一直在混用PHP和jquery脚本,但是我没有成功修改代码以执行我想要的事情。任何帮助将不胜感激。

ajaxData.php

<?php
//Include the database configuration file
include 'dbConfig.php';

if(!empty($_POST["country_id"])){
    //Fetch all state data
    $query = $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");

    //Count total number of rows
    $rowCount = $query->num_rows;

    //State option list
    if($rowCount > 0){
        echo '<option value="">Select state</option>';
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
        }
    }else{
        echo '<option value="">State not available</option>';
    }
}elseif(!empty($_POST["country_id"])){
    //Fetch all city data
    $query = $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['country_id']." AND status = 1 ORDER BY city_name ASC");

    //Count total number of rows
    $rowCount = $query->num_rows;

    //City option list
    if($rowCount > 0){
        echo '<option value="">Select city</option>';
        while($row = $query->fetch_assoc()){ 
            echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
        }
    }else{
        echo '<option value="">City not available</option>';
    }
}
?>

index.php

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Dynamic Dependent Select Boxes by CodexWorld</title>
<meta charset="utf-8">
<style type="text/css">
.container{width: 280px;text-align: center;}
select option{
    font-family: Georgia;
    font-size: 14px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('#country').on('change',function(){
        var countryID = $(this).val();
        if(countryID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'country_id='+countryID,
                success:function(html){
                    $('#state').html(html);
                    $('#city').html('<option value="">Select state first</option>'); 
                }
            }); 
        }else{
            $('#state').html('<option value="">Select country first</option>');
            $('#city').html('<option value="">Select state first</option>'); 
        }
    });

    $('#state').on('change',function(){
        var stateID = $(this).val();
        if(stateID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#city').html(html);
                }
            }); 
        }else{
            $('#city').html('<option value="">Select state first</option>'); 
        }
    });
});
</script>
</head>
<body>
<div class="container">
    <?php
    //Include the database configuration file
    include 'dbConfig.php';

    //Fetch all the country data
    $query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");

    //Count total number of rows
    $rowCount = $query->num_rows;
    ?>
    <select id="country">
        <option value="">Select Country</option>
        <?php
        if($rowCount > 0){
            while($row = $query->fetch_assoc()){ 
                echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
            }
        }else{
            echo '<option value="">Country not available</option>';
        }
        ?>
    </select>

    <select id="state">
        <option value="">Select country first</option>
    </select>

    <select id="city">
        <option value="">Select state first</option>
    </select>
</div>
</body>
</html>

创建表countries(   country_id int(11)NOT NULL,   country_name varchar(50)字符集utf8不为空,   status tinyint(1)非空默认值'1'注释'0:已阻止,1:处于活动状态' )ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;

CREATE TABLE `states` (

state_id int(11)非空,   state_name varchar(50)收集utf8_unicode_ci NOT NULL,   country_id int(11)NOT NULL,   status tinyint(1)非空默认值'1'注释'0:已阻止,1:处于活动状态' )ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;

ALTER TABLE states   添加主键(state_id);

ALTER TABLE states   修改state_id int(11)NOT NULL AUTO_INCREMENT; 提交;

CREATE TABLE cities (

city_id int(11)NOT NULL,   city_name varchar(50)收集utf8_unicode_ci NOT NULL,   state_id int(11)非空,   状态tinyint(1)非空默认值'1'注释'0:已阻止,1:有效' )ENGINE = InnoDB DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;

ALTER TABLE城市   添加主键(city_id);

ALTER TABLE城市   修改city_id int(11)NOT NULL AUTO_INCREMENT;

1 个答案:

答案 0 :(得分:2)

我无法复制或测试您的AJAX调用,并且您未提供数据结构的示例。我建议您使用AJAX填充所有内容,而不要混入PHP。考虑下面的代码。

var countries = [{
    value: "us",
    label: "United States",
    states: [{
      value: "ca",
      label: "California",
      cities: [{
        value: "sf",
        label: "San Francisco"
      }, {
        value: "la",
        label: "Los Angeles"
      }]
    }, {
      value: "or",
      label: "Oregon"
    }, {
      value: "wa",
      label: "Washington"
    }]
  }, {
    value: "mx",
    label: "Mexico"
  },
  {
    value: "ca",
    label: "Canada"
  }
];
$(function() {
  function populateSelect(arr, tObj) {
    $("<option>").appendTo(tObj);
    $.each(arr, function(k, v) {
      $("<option>", {
        value: v.value
      }).data("id", k).html(v.label).appendTo(tObj);
    });
  }

  populateSelect(countries, $("#country"));
  $("#state").width($("#country").width() + "px");
  $("#city").width($("#country").width() + "px");

  $('#country').on('change', function(e) {
    var c = $("option:selected", this).data("id");
    populateSelect(countries[c].states, $("#state"));
    $("#state").prop("disabled", false);
    /*
    $.ajax({
      type: 'POST',
      url: 'ajaxData.php',
      data: JSON.stringinfy({'country_id': c}),
      success: function(resp) {
        populateSelect(resp, $('#state'));
      }
    });
    */
  });

  $('#state').on('change', function(e) {
    var c = $("#country option:selected").data("id");
    var s = $("option:selected", this).data("id");
    populateSelect(countries[c].states[s].cities, $("#city"));
    $("#city").prop("disabled", false);
    /*
    $.ajax({
      type: 'POST',
      url: 'ajaxData.php',
      data: JSON.stringinfy({'state_id': s}),
      success: function(resp) {
        populateSelect(resp, $('#cities'));
      }
    });
    */
  });
});
.container {
  width: 280px;
  text-align: center;
}

.container ul {
  padding: 0;
  margin: 0;
  list-style: none;
}

.container ul li label {
  width: 120px;
  display: inline-block;
}

select option {
  font-family: Georgia;
  font-size: 14px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="container">
  <ul>
    <li>
      <label>Country</label>
      <select id="country">
      </select>
    </li>
    <li>
      <label>State</label>
      <select id="state" disabled="true">
      </select>
    </li>
    <li>
      <label>City</label>
      <select id="city" disabled="true">
      </select>
    </li>
  </ul>
</div>

在注释中,您可以看到要使用AJAX进行的操作。结构将是相同的:

[
  {
    value,
    label
  }
];

我建议这样做,因为您可以根据需要轻松使用jQuery UI Autocomplete

希望这会有所帮助。