doubo4336 2016-02-04 22:06
浏览 93
已采纳

使用PHP和MySQL在另一个下拉列表中填充一个下拉列表

I have a dropdown which gets the information from a query using mysqli_query() now, once selecting a choice from the first dropdown I want the second dropdown to be filled with data from a difference query.

This is my code

HTML:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
    $('.country').on('change', function() {
    // Code to add country information in url
    location.href = location.href.split('?')[0]
        + ['?country', $(this).val()].join('=');
    });
});
</script>

PHP First dropdown:

<?php
    $countries = mysqli_query($mysqli,"select source from nhws.masterkey group by source;");
    echo "<select name='country' style=width:200px>"; 
    echo "<option size =30 ></option>";
    while($row = mysqli_fetch_array($countries)){        
        echo "<option value='".$row['source']."'>".$row['source']."</option>"; 
    }
    echo "</select>";
?>

PHP Second dropdown:

<?php
if (isset($_GET['country'])) {
   $country = $_GET['country'];
   echo $country;
   $variables = mysqli_query($mysqli,"select variable from nhws.num_all_{$country} group by variable;");
   echo "<select name='variable' style=width:200px>"; 
   echo "<option size =30 ></option>";
   while($row = mysqli_fetch_array($variables)) {        
     echo "<option value='".$row['variable']."'>".$row['variable']."</option>"; 
   }
   echo "</select>";
}
?>

Now, once a selection was choosen from the first dropdown nothing happens in the second dropdown.

Thanks!

  • 写回答

1条回答 默认 最新

  • dongwang3066 2016-02-04 22:19
    关注

    I assume you can use jQuery. So add a jQuery listener like this:

    <script>
    $(document).ready(function() {
        $('.country').on('change', function() {
            // Code to add country information in url
            location.href = location.href.split('?')[0]
                + ['?country', $(this).val()].join('=');
        });
    });
    </script>
    

    Now on php code at the top add something like this after the code you mentioned

    if (isset($_GET['country']) {
        $country = $_GET['country'];
        // code to prevent SQL injection
        // ... code to get data from DB using country name
        // ... code to print a new select box based on data from DB
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制