如何从mysql / php中的json对象中选择数据?

时间:2021-11-25 07:09:47

I'm sending JSON to my server via jQuery's ajax method. Here's my jquery, and im pretty sure this is fine:

我通过jQuery的ajax方法将JSON发送到我的服务器。这是我的jquery,我很确定这很好:

function stuffs() {
    this.fname = document.getElementById("fname").value;
    this.lname = document.getElementById("lname").value;
    this.email = document.getElementById("email").value;    
}
$(function() {
function ajaxhelper(data){
    //console.log(JSON.stringify(data));
    //this returns "{"fname":"mike","lname":"smith","email":"a@a.a"}" which is what i expect
        $.ajax({
        url: 'postdb.php',
        type: 'POST',
        data: {data : JSON.stringify(data)},
        success: function(data) {
            console.log(JSON.stringify(data));
            console.log("Success");
        },
        error: function(e) {
            console.log(e);
        }

    });
}
$("form").on('submit', function(e){
    e.preventDefault();
    var data = new stuffs();
    ajaxhelper(data);
    //window.location = "postdb.php";
    });
    });
</script>

I get back an 500 server error. Here's my php code. (yes i'm only sending it an fname that i've preloading into my database, $con is valid i just didnt share the code to connect to my database)

我收到500服务器错误。这是我的PHP代码。 (是的,我只发送一个fname,我已预加载到我的数据库,$ con有效,我只是没有共享代码连接到我的数据库)

$obj = json_decode($_POST['data']);

$sql = "SELECT * FROM testtable WHERE fname = \"$obj->{'fname'}\"";
$query = $con->query($sql);

I think my sql is incorrect due to the quotes? This is where im stuck.

由于引号,我认为我的sql不正确?这就是我陷入困境的地方。

2 个解决方案

#1


2  

Try using $obj->fname instead of $obj->{'fname'}.

尝试使用$ obj-> fname而不是$ obj - > {'fname'}。

#2


0  

Here is the correct syntax for your SQL Statement

以下是SQL语句的正确语法

$sql = "SELECT * FROM testtable WHERE fname = '".$obj->fname."'";

$ sql =“SELECT * FROM testtable WHERE fname ='”。$ obj-> fname。“'”;

#1


2  

Try using $obj->fname instead of $obj->{'fname'}.

尝试使用$ obj-> fname而不是$ obj - > {'fname'}。

#2


0  

Here is the correct syntax for your SQL Statement

以下是SQL语句的正确语法

$sql = "SELECT * FROM testtable WHERE fname = '".$obj->fname."'";

$ sql =“SELECT * FROM testtable WHERE fname ='”。$ obj-> fname。“'”;