Insert JSON file into database via PHP

Asked

Viewed 587 times

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)?

1 answer

1


The most external json key retorno foreach tries to iterate it and does not give the expected result, in which case you must specify where it varies or indicate in 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.