2015-10-13 98 views
1

我必須從下拉列表中選擇城市並根據值我必須進一步檢索屬於該城市的人使用jquery 我的代碼是如何從下拉列表中插入數值到mysql查詢以檢索數據庫中的數據

<select class="form-control" id="personCity"> 
      <option class="form-control" value="">Person country</option> 
      <option class="form-control" value="usa">usa</option> 
      <option class="form-control" value="aus">Australia/option> 
</select> 

我有使用jquery

$('#personCity').change(function(e) { 
    var personCity=$('#personCity').val(); 
    $('#personcityRetrive').text(personCity); 
}); 

,並獲得價值的數據庫我有以下數據

country  person 
usa   abc 
aus   xyz 
usa   123 
aus   ABC 

MySQL的代碼是

<?php 
$sql=mysql_query("SELECT * FROM outlets WHERE country='" 
?><span id="personcityRetrive"></span> 
<?php "'");?> 
+0

PHP在服務器上運行之前,HTML和JavaScript被髮送到瀏覽器。 Javascript在瀏覽器上運行。做你想做的事情的唯一方法是使用Ajax調用返回到服務器以獲取數據。然後將響應發送回瀏覽器並在div中插入響應。查看關於使用PHP做Ajax的教程。親自嘗試一下,如果你有問題,請在另一個問題的幫助下發布你的代碼。 http://iviewsource.com/codingtutorials/learning-how-to-use-jquery-ajax-with-php-video-tutorial/ –

回答

0

鑑於這種HTML:

<select class="form-control" id="personCity"> 
    <option class="form-control" value="">Person country</option> 
    <option class="form-control" value="usa">usa</option> 
    <option class="form-control" value="aus">Australia/option> 
</select> 

您需要執行AJAX時的變化情況。 jQuery的:

$('#personCity').change(function(e) { 
    var personCity=$('#personCity').val(); 
    $.get('lookupCity.php', { "city": personCity }, function(result){ 
     $("#personcityRetrive").html(result); 
    }); 
}); 

你的PHP需要獨立(lookupCity.php),連接到SQL Server,和回聲一個SQL查詢的結果。它不應該使用MySQL函數,這些已被棄用。你也想避免SQL注入。試試這個:

<?php 
$link = mysqli_connect("localhost", "my_user", "my_password", "world"); 
if (mysqli_connect_errno()) { 
    printf("Connect failed: %s\n", mysqli_connect_error()); 
    exit(); 
} 
if ($stmt = mysqli_prepare($link, "SELECT person FROM outlets WHERE country=? LIMIT 1"); 
    mysqli_stmt_bind_param($stmt, "s", $_GET['city']); 
    mysqli_stmt_execute($stmt); 
    mysqli_stmt_bind_result($stmt, $person); 
    mysqli_stmt_fetch($stmt); 
    printf("%s\n", $person); 
    mysqli_stmt_close($stmt); 
} 
mysqli_close($link); 
?> 
相關問題