2017-05-31 34 views
1

我有一個國家城市數據庫,在選擇框中顯示,一切工作正常。當我選擇狀態選擇框來顯示城市結果的div或其他元素時,我想要什麼。當選擇框城市結果定義是沒有問題的,但如果我使用DIV提供錯誤消息Mysql與jquery post的選擇框

注意:未定義指數:國家在C:\ WAMP \ WWW \在第3行

列表\ post.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); 
     }); 
}); 

的index.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> 
+1

您的代碼容易受到[** SQL注入**](https://en.wikipedia.org/wiki/SQL_injection)攻擊。你應該使用[** mysqli **](https://secure.php.net/manual/en/mysqli.prepare.php)或[** PDO **](https://secure.php.net/ manual/en/pdo.prepared-statements.php)準備帶有綁定參數的語句,如[**這篇文章**]所述(https://stackoverflow.com/questions/60174/how-can-i-prevent-sql步噴射功能於PHP)。 –

回答

0

的腳本需要CHE eck是否使用countrystate參數調用它,並執行相應的查詢。和返回的州一樣,返回城市的代碼需要將它們放入<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注入。在那之前,你至少應該逃避參數。