I'm having trouble solving a problem and I'm counting on your help. I am getting, from an external API, an HTTP POST request in JSON format with some information. I need to get this information separately and do an UPDATE on MYSQL using PDO. The API sends the information in the following format:
{"type":"info-type","clientId":"info-client","sku":"info-sku","quantity":info-quantity }
I did the following to receive and update the database:
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *);
require('../../config.php');
$json_str = file_get_contents("php://input");
$obj = json_decode($json_str, true);
$sku = "$obj->sku";
$quantity = "$obj->quantity";
print_r($obj);
try {
$pdo = new PDO('mysql:host=' . DB_HOSTNAME . ';port=' . DB_PORT . ';dbname=' . DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('UPDATE bg_product SET quantity = :quantity WHERE sku = :sku');
$stmt->execute(array(
':sku' => $sku,
':quantity' => $quantity
)
);
echo $stmt->rowCount();
}catch(PDOException $e) {
echo 'erro no banco de dados';
}
?>
I noticed that before going through json_decode it looks like this:
"{\"type\":\"info-type\",\"clientId\":\"info-client\",\"sku\":\"info-sku\",\"quantity\":info-quantity}"
And then it shows correctly:
{"type":"info-type","clientId":"info-client","sku":"info-sku","quantity":info-quantity }
The error message I receive from PHP is as follows: PHP Notice: Trying to get property of non-object. Well in this lines:
$sku = "$obj->sku";
$quantity = "$obj->quantity";
I made a var_dump and the following appears:
string(99) "{"type":"info-type","clientId":"info-client","sku":"info-sku","quantity":info-quantity}"
It looks like it's not moving to an Array properly:
Thank you in advance.