在第二个下拉列表中下拉选定的值

时间:2014-02-12 10:06:47

标签: php sql drop-down-menu selecteditem selectedvalue

我想从"list_cust_name"中选择值,并希望将其传递给另一个查询以获取"list_cust_city"的列表。此列表将显示从"list_cust_name"中选择的客户的城市。我的表包含cust_id,cust_name,cust_city_cust_state。

 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
 <script>
 $(function() {
 $('#list_cust_name').change(function(){
  $.ajax({
         url:'city.php',
        data:{cust_name:$( this ).val()},
        success: function( data ){
                $('#list_cust_city').html( data );
        }
 });
  });
  });
 </script>

 <label style="color:#000">Name </label>
 <?php $data_name = mysql_query("SELECT DISTINCT cust_name FROM customer_db ORDER BY    cust_name");?>

 <select id="list_cust_name" name="list_cust_name">
 <?php while($fetch_options_name = mysql_fetch_assoc($data_name)) { ?> 
 <option value="<?php=$fetch_options_name['cust_name']; ?>"><? php=$fetch_options_name['cust_name']; ?></option>
 <?php } ?>
 </select>

 <select id="list_cust_city" name="list_cust_city"></select>


 city.php

 <?php 
 include('dbconnect.php');
 db_connect();
  $cust_name1=$_GET['cust_name'];
  $data_city = mysql_query('SELECT DISTINCT cust_city FROM customer_db WHERE cust_name="'.$cust_name1.'" ORDER BY cust_city');
  while($fetch_options_city = mysql_fetch_assoc($data_city)) {
  ?> 
  <option value="<?php=$fetch_options_city['cust_city'];?>"><?php=$fetch_options_city['cust_city'];?></option>
  <?php
  }   
  ?>

1 个答案:

答案 0 :(得分:0)

我从select中删除了id =“list_cust_city”,把它放到包含select的div中,使得ajax返回一个完整的Select并将它放在div中。并为$ GET添加了mysql_real_escape_string以防止mysql注入。您应该考虑开始使用mysqli或PDO,因为不推荐使用mysql *。

 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
 <script>
 $(function() {
 $('#list_cust_name').change(function(){
  $.ajax({
         url:'city.php',
        data:{cust_name:$( this ).val()},
        success: function( data ){
                $('#list_cust_city').html( data );
        }
 });
  });
  });
 </script>

 <label style="color:#000">Name </label>
 <?php $data_name = mysql_query("SELECT DISTINCT cust_name FROM customer_db ORDER BY    cust_name");?>

 <select id="list_cust_name" name="list_cust_name">
 <?php while($fetch_options_name = mysql_fetch_assoc($data_name)) { ?> 
 <option value="<?php=$fetch_options_name['cust_name']; ?>"><? php=$fetch_options_name['cust_name']; ?></option>
 <?php } ?>
 </select>
 <div id="list_cust_city">
 <select name="list_cust_city"></select>
 </div>


 city.php

 <?php 
 include('dbconnect.php');
 db_connect();
  $cust_name1=mysql_real_escape_string($_GET['cust_name']);
  $data_city = mysql_query("SELECT DISTINCT cust_city FROM customer_db WHERE cust_name='$cust_name1' ORDER BY cust_city");
?>
<select name="list_cust_city">
<?php
  while($fetch_options_city = mysql_fetch_assoc($data_city)) {
  ?> 
  <option value="<?php=$fetch_options_city['cust_city'];?>"><?php=$fetch_options_city['cust_city'];?></option>
  <?php
  }   
  ?>
</select>