如何将值从下拉列表插入到mysql查询中以从数据库中检索数据

时间:2015-10-13 20:48:47

标签: php jquery mysql ajax html5

我必须从下拉表中选择城市并根据价值我必须使用jquery进一步检索属于该城市的人 我的代码是

 <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 "'");?>

1 个答案:

答案 0 :(得分: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 Lookup的结果。它不应该使用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);
?>
相关问题