根据第一个选择列表值填充第二个选择列表

时间:2016-08-02 19:00:08

标签: php forms

我试图做一个不起作用的嵌套选择列表第二个选择列表的值不会被填充。这是我的代码。我填充第一个选择并基于其值getter.php被动态调用以填充第二个选择框(不起作用)

<div class="col-sm-3">
    <label for="rg">Region</label>
</div>
<div class="col-sm-9">
    <select id="region" name="region">
        <option value="">Select Region</option>
        <option value="AR">Ashanti</option>
        <option value="BRONG+AHAFO">Brong Ahafo</option>
        <option value="CENTRAL">Central</option>
        <option value="EASTERN">Eastern</option>
        <option value="GREATER+ACCRA">Greater Accra</option>
        <option value="NORTHERN">Northern</option>
        <option value="UPPER+EAST">Upper East</option>
        <option value="UPPER+WEST">Upper West</option>
        <option value="VOLTA">Volta</option>
        <option value="WESTERN">Western</option>
    </select>
</div>

<div class="col-sm-3"><label for="tw">Town</label></div>
<div class="col-sm-9">
    <select id="town" name="town">
        <option value="">Select Town</option>

    </select>
</div>


<script type="text/javascript">
$(document).ready(function() {
    $("#region").change(function() {
        $("#town").load("getter.php?choice=" + $("#region").val());
    });
});
</script>

这是getter.php

<?php
include "../areashoppers/includes/cs_functions.php";
$sql = "SELECT distinct town FROM oic_areas_full WHERE region = '".$choice."' ORDER BY town ASC";
$st = $sc_conn->query($sql);
while ($r = $st->fetch()) {
    echo "<option>" . $r['town'] . "</option>";
}
?>

这是错误日志中显示的内容

  

[02-Aug-2016 18:39:50 UTC] PHP注意:未定义的变量:第3行/home/areashoppers/public_html/nylb/getter.php中的选择

     

[02-Aug-2016 18:39:50 UTC] PHP致命错误:在第5行的/home/areashoppers/public_html/nylb/getter.php中调用boolean上的成员函数fetch()

$ sc_conn是我在cs_functions中定义的DSN

2 个答案:

答案 0 :(得分:2)

Undefined variable: choice最有可能导致第二个错误,因为如果未定义$choice,查询将失败。

$choice = $_GET['choice'];
PHP脚本开头的

应该清除错误。

getter.php?choice=something等查询字符串中包含变量不会自动创建$choice变量,但 会将值存储在$_GET['choice']中。

如果您想在查询中安全地使用$choice变量,请不要担心转义它,只需使用预准备语句即可。假设$sc_conn是一个有效的PDO连接,那将是这样的:

$sql = "SELECT distinct town FROM oic_areas_full WHERE region=? ORDER BY town ASC";
$st = $sc_conn->prepare($sql);
$st->execute([$choice]);

答案 1 :(得分:0)

你必须通过GET方法从网址中做出选择。

<?php
include "../areashoppers/includes/cs_functions.php";
$choice = $_GET['choice'];
$sql = "SELECT distinct town FROM oic_areas_full WHERE region='$choice' ORDER BY town ASC";
$st = $sc_conn->query($sql);
while ($r = $st->fetch()) {
  echo "<option>" . $r['town'] . "</option>";
}
?>