1
I have a JSON file that I need to do the Insert of the information contained in it in the database.
JSON file:
{"retorno":{"produtos":[{"produto":{"codigo":"AAAAAA","estoqueAtual":20}},{"produto":{"codigo":"BBBBBB","estoqueAtual":10}}]}}
How I’m Trying to Make Insert:
<?php
$db = new PDO('mysql:host=localhost;dbname=dbname','root','');
$jsondata = file_get_contents('bling.json');
$data = json_decode($jsondata, true);
$stmt = $db->prepare("insert into bling values(?,?)");
foreach ($data as $row) {
$stmt->bindParam(1, $row['produtos']['produto']['codigo']);
$stmt->bindParam(2, $row['produtos']['produto']['estoqueAtual']);
$stmt->execute();
}
?>
However, in this way, I cannot enter any information in the database.
If I do it that way, adding the [0]
it works:
foreach ($data as $row) {
$stmt->bindParam(1, $row['produtos'][0]['produto']['codigo']);
$stmt->bindParam(2, $row['produtos'][0]['produto']['estoqueAtual']);
$stmt->execute();
}
But it only takes the first value (0) of the JSON file. If I put [1]
he takes the second value, and so on.
I needed a suggestion on how to improve the code so I can capture and insert into the database all the values that are within JSON.
When you var_dump $data how does it look? have you tried adding the "key" field in foreach? foreach ($date as $key => $Row)?
– Diego Braga