Insert JSON file into the database via PHP

1

I have a JSON file that I need to insert the information contained in it into the database.

JSON file:

{"retorno":{"produtos":[{"produto":{"codigo":"AAAAAA","estoqueAtual":20}},{"produto":{"codigo":"BBBBBB","estoqueAtual":10}}]}}

How I'm trying to 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, I can not enter any information in the database.

If I do this in the same way, adding [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] it gets the second value, and so on.

I needed a hint on how to improve the code so that I can capture and insert into the database all values that are within JSON.

    
asked by anonymous 26.10.2017 / 21:38

1 answer

1

The outermost key of json retorno foreach tries to iterate it and does not give the expected result, in this case you must specify where it varies or indicate in the foreach.

Change:

foreach ($data as $row) {

To:

foreach ($data['retorno']['produtos'] as $row) {
   $stmt->bindParam(1, $row['produto']['codigo']);
   $stmt->bindParam(2, $row['produto']['estoqueAtual']);

   $stmt->execute();
}
    
26.10.2017 / 21:53