jonmrich jonmrich - 3 months ago 6x
PHP Question

Handle POST request in JSON format

I'm trying to handle a POST request from a web service. It's sending an HTTP POST request like this:


It's posting to a PHP file on my server. I know that it is hitting the file for sure. However, I'm not getting the data.

In my PHP, I have this (leaving out a bunch of stuff:

$json = file_get_contents('php://input');
$obj = json_decode($json);
$mine ="sixteen"; //using this for a test

$sql = "INSERT INTO rr_emergency (random) VALUES('$obj');";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);

This makes no change to my database.

If I do this instead:

$sql = "INSERT INTO rr_emergency (random) VALUES('$mine');";

Then "sixteen" is added in the right spot in a new row in my table each time the webservice calls my PHP. This is how I know I'm receiving data.

NOTE: I was trying to simply add
into my table just to see the data format that's returned before I tried to properly parse it and put everything where it belongs.

What am I doing wrong here? I think the problem is here (
$json = file_get_contents('php://input');
), but not sure what else to try.



So there's a few problems

$obj = json_decode($json);

This will return an object. You want an array

$obj = json_decode($json, true);

Then your PDO is incorrect

$sql = "INSERT INTO rr_emergency (random) VALUES(:val);";
$prep = $dbh->prepare($sql);
foreach($obj as $row) $prep->execute([':val' => $row]);

This will insert your data correctly (using a prepared statement) and loop over the JSON return data