want to receive json data sent via ajax using php and store it in db

时间:2016-03-02 10:48:22

标签: php jquery json ajax

following is my js

            var obj = {};
            obj["name"] = uname;
            obj["repo"] = repo;
            obj["length"] = linelength;
            var json = JSON.stringify(obj);
            $.ajax({
                method: "POST",
                url: "example.php",
                data: {'data' : json},
                success: function(response){
                    console.log("success");
                }
            });

and following is my php

<?php
include("connection.php");
if(isset($_POST["data"])){
    $myData = $_POST["data"];
    $ddata = json_decode($myData);
    $name = $ddata->name;
    $repo = $ddata->repo;
    $length = $ddata->length;
    $query = "INSERT INTO user('name', 'repo', 'length') VALUES($name, $repo, $length)";
    $db->exec($query);
}   ?>

The log is showing success but the data are not getting added in db. Your help will be appreciated

3 个答案:

答案 0 :(得分:0)

Column names should be enclosed (if at all) with backticks ` and values enclosed in single quotes ':

$query = "INSERT INTO user (`name`, `repo`, `length`)
          VALUES ('$name', '$repo', '$length')";

However, I would say that your code is vulnerable to injection and you should use placeholders - switch to using prepared statements!

答案 1 :(得分:0)

remove ' on your columns names and put inputs in 2 ' :

$query = "INSERT INTO user(name, repo, length) VALUES('$name', '$repo', '$length')";

答案 2 :(得分:0)

$query = "INSERT INTO user(name,repo,length) VALUES('".$name."','".$repo."','".$length."')";