在json_decode之后获取空数据

时间:2017-06-30 08:12:01

标签: php mysql sql

我使用Angular的Http Post方法,我得到一个输出

data={"firstname":"sandeep","lastname":"chetikam","city":"Hyderabad","dateofbirth":"2017-06-08","gender":"Male"}

所以我是json_decoding数据,但我无法从中获取值。 当我将数据插入Sql查询。我得到一个空值

PHP代码:

<?php 
header('Aceess-Control-Header-Origin: *');
include('connect_db.php');
$post = json_decode($_POST['data']);
$id= "$post.id";
$firstname="$post.firstname";
$lastname="$post.lastname";
$dateofbirth="$post.dateofbirth";
$city="$post.city";
$gender="$post.gender";


$sql = "INSERT INTO employees(firstname,lastname,dateofbirth,city,gender) VALUES ("$firstname",".$lastname.",".$dateofbirth.",".$city.",".$gender.")";
if (mysqli_query($conn,$sql)) {
    echo "DATA has been submitted";
}else{
    echo "error".mysqli_error($conn);
}
echo json_encode("Successful");
?>

我调用数据错了吗?如何将数据值调用到我的Sql查询中。请帮忙。

修改:

    <?php 
    header('Aceess-Control-Header-Origin: *');
    include('connect_db.php');

    $post =json_decode($_POST['data'], true);
    $id= $post->id;
    $firstname=$post->firstname;
    $lastname=$post->lastname;
    $dateofbirth=$post->dateofbirth;
    $city=$post->city;
    $gender=$post->gender;


    $sql = "INSERT INTO employees(firstname,lastname,dateofbirth,city,gender) VALUES (".$firstname.",".$lastname.",".$dateofbirth.",".$city.",".$gender.")";
    if (mysqli_query($conn,$sql)) {
        echo "DATA has been submitted";
    }else{
        echo "error".mysqli_error($conn);
    }
    echo json_encode("Successful");
    ?>

现在我没有从查询中获得任何输出。

这是我的HTTP POST调用的输出: 表格数据:

data:{"firstname":"Dwqd","lastname":"chetikamqdqwdqwd","city":"Hyderabad","dateofbirth":"2017-06-02","gender":"Male"}

2 个答案:

答案 0 :(得分:1)

php不使用点(。)字符来访问属性。您需要使用箭头 - &gt;。因此,要访问您使用的性别。

$gender = $post->gender;

答案 1 :(得分:0)

您必须使用' - &gt;'来获取php中的对象值,并且您错过了我们的查询'。

所以只需替换这个

$id= "$post.id";
"INSERT INTO employees(firstname,lastname,dateofbirth,city,gender) VALUES ("$firstname",".$lastname.",".$dateofbirth.",".$city.",".$gender.")";

 $id= $post->id;
 "INSERT INTO employees(firstname,lastname,dateofbirth,city,gender) VALUES (".$firstname.",".$lastname.",".$dateofbirth.",".$city.",".$gender.")";

它适用于你。