通过 getJSON 将变量发送到数据库查询的最佳方法是什么?


What is the best way to send variable via getJSON to database query?

我有以下代码...我正在尝试传入一个参数以用值替换"id = 0"。 有没有办法做到这一点,或者有更好的方法?

数据库调用

include 'db.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM myTable where id = 0;");

JSON调用:

$(function(){
    var items="";
    $.getJSON("mypage.php",function(data){
        $.each(data,function(index,item) {
        items+="<option value='"+item.id+"'>"+item.title+"</option>";
        });
        // .... some stuff
    });
});

你可以解析抛出getJSON请求的变量。

执行以下操作:

$.getJSON("mypage.php", {id : 2}, function(data){
    // .... some stuff
});

PHP 通过 GET 接收变量:

include 'db.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$id = $_GET["id"]; 
$result = mysql_query("SELECT * FROM myTable where id = ".mysql_real_escape_string($id).";");

确保使用 mysql_real_escape_string() 来防止 mysql 注入...