-4

I'm looking for a php code to read the JSON object (which I'm going to upload using Android into the url) and I also want the php function to insert the data into my db. Can someone please help me? This is my JSON object

{
"id": "mID",
"description": "des",
"stars": "mStars",
"name": "avatar",
"year": "mYear",
"rating": "mRating",
"director": "mDirector"
"url": "www.dummy.com"
}

this is my php code

    $app->post(
    '/post/',
    function () use ($app){
        echo 'This is a POST route';
        $json = $app->request->getBody();
        $data = json_decode($json, true);
        echo $data['name'];
        echo $data['id'];
        echo $data['description'];
        echo $data['stars'];
        echo $data['rating'];
        echo $data['director'];
        echo $data['url'];
        echo $data['year'];
        createMovie($data);
    }
);
    The following code is in a separate file. I have similar files with select statements which are working perfectly fine.

    <?php
    function createMovie($data) {
    $conn=getDB();
    if($stmt=$conn->prepare("$sql="INSERT INTO Movies (id,        name,description, director, year, rating, stars, url)
VALUES   ($data['id'],$data['name'],$data['description'],$data['director'],$data['year'],$data['rating'],$data['stars'],$data['url'])";
   {
      $stmt->execute();
      $conn->close();
   }    
  }
        ?>

when I type www.example.com/post/ I'm getting Error 404 not found

1 Answers1

2

Use json_decode() like so:

<?php
$jsonData = '{ "user":"John", "age":22, "country":"United States" }';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) { 
    echo "<p>$key | $value</p>";
}
?>

Here is the link to the official documentation of the function.

Ahs N
  • 8,233
  • 1
  • 28
  • 33
  • 1
    Correct answer, you should however add a link to the functions documentation. And... a single debug output is enough, so the `print_r()` :-) More only confuses and does not help any further. – arkascha Jun 26 '15 at 08:19