Prakash
Prakash

Reputation: 71

Getting Empty data after json_decode

I using a Http Post method for Angular and I am getting an output as

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

So i am json_decoding the data but i am not able to get the values from it . When i Insert the data into Sql query. I am getting a empty values

PHP code:

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

Am i calling the data wrong ? How to call data values into my Sql query. Please help.

Modified :

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

Now i am not getting any output from the query.

This is the output from my HTTP POST call : FORM Data:

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

Upvotes: 0

Views: 59

Answers (2)

Bibhudatta Sahoo
Bibhudatta Sahoo

Reputation: 4894

You have to use '->' to get the object value in php and you miss to give '.' on our query

So just replace this

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

with

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

It will work for you.

Upvotes: 0

Dan Hastings
Dan Hastings

Reputation: 3280

php doesnt use the dot (.) character to access properties. You need to use the arrow ->. So to access the gender you use.

$gender = $post->gender;

Upvotes: 1

Related Questions