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

标签 php jquery mysql ajax html

我必须从下拉表中选择城市,并根据值我必须使用 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 "'");?>

最佳答案

给定这个 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 注入(inject)。试试这个:

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

关于php - 如何将下拉列表中的值插入到 mysql 查询中以从数据库中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33112353/

相关文章:

PHP,验证用户提交的具有特定域的 URL

PHP 困惑检测器给出误报

javascript - 用@标记用户

python - 复合 SQL INSERT 语句

MySQL LEFT Join 显示不正确的数据

php - 如何为 <br> 标签添加边距?

javascript - 比较两个数组中的多个对象

javascript - 更改时的图像预览不起作用

php - 无法使用常量链接图像

javascript - 从标签输入中获取值到 Twitter typeahead js