1

我有一个国家城市数据库,显示在选择框中,一切正常。What i want when state select box selected to display city results in a div or another element. 当为城市结果定义选择框时没有问题,但如果我使用 div 会给出错误消息

注意:未定义的索引:第 3 行 C:\wamp\www\list\pos​​t.php 中的国家/地区。

这是我的代码,谢谢。

post.php

include("connect.php");
$country = $_POST['country'];
$query = mysqli_query($connect, "select * from state where country_id='$country'");

while( $list = mysqli_fetch_array( $query ) ) {
    echo '<option value=' . $list["id"]. '>' . $list["state_name"] . '</option>';
}

 $state = $_POST['state'];
$query = mysqli_query($connect, "select * from city where state_id='$state'");

while( $list = mysqli_fetch_array( $query ) ) {
    echo $list["city_name"];
}

jQuery代码

$( "#countries" ).change( function(){
    $("#states").empty();
    var val = $(this).val();
    $.post("post.php", {country:val}, function(a) {
        $("#states").append(a);
        });
});

$( "#states" ).change( function(){
    $("#cities").empty();
    var val = $(this).val();
    $.post("post.php", {state:val}, function(a) {
        $("#cities").append(a);
        });
});

索引.php

<?php include("connect.php"); ?>
<select id="countries">
<option>select</option>
<?php
$query = mysqli_query($connect, 'select * from country');
while( $list = mysqli_fetch_array( $query ) ) {
    echo '<option value=' . $list["id"]. '>' . $list["country_name"] . '</option>';
}
?>
</select>

<select id="states">
<option>select</option>
</select>

<div id="cities"></div>
4

1 回答 1

0

该脚本需要检查是否使用countryorstate参数调用它,并执行适当的查询。并且返回城市的代码需要将它们放入<option>,就像返回状态一样。

include("connect.php");
if (isset($_POST['country'])) {
    $country = mysqli_real_escape_string($connect, $_POST['country']);
    $query = mysqli_query($connect, "select * from state where country_id='$country'");

    while( $list = mysqli_fetch_array( $query ) ) {
        echo '<option value=' . $list["id"]. '>' . $list["state_name"] . '</option>';
    }
elseif (isset($_POST['state'])) {

    $state = mysqli_real_escape_string($connect, $_POST['state']);
    $query = mysqli_query($connect, "select * from city where state_id='$state'");

    while( $list = mysqli_fetch_array( $query ) ) {
        '<option value=' . $list["id"]. '>' . $list["city_name"] . '</option>';
    }
}

您还应该学习使用参数化查询而不是替换变量,以防止 SQL 注入。在那之前,您至少应该转义参数。

于 2017-05-31T21:06:13.143 回答