简体   繁体   中英

How do I extract data from JSON and insert it in MySQL with PHP?

I need to extract data from a JSON fila and insert it in MySQL with PHP. This is the code,

<?php
  $connect = mysqli_connect("localhost", "root", "pass", "dbname"); //Connect PHP to MySQL Database
  $query = '';
  $table_data = '';
  $filename = "organizations.json";
  $data = file_get_contents($filename); //Read the JSON file in PHP
  $array = json_decode($data, true); //Convert JSON String into PHP Array
  foreach($array as $row) //Extract the Array Values by using Foreach Loop - "Inserto todos los campos en la tabla pero no muestro el 'id' en la web"
  {
   $query .= "INSERT INTO organizations(id, displayName, created) VALUES ('".$row["id"]."', '".$row["displayName"]."', '".$row["created"]."'); ";  // Make Multiple Insert Query 
   $table_data .= '
        <tr>
    <td>'.$row["displayName"].'</td>
    <td>'.$row["created"].'</td>
</tr>
   '; //Data for display on Web page
  }

The code works fine with the following json file:

[
    {
      "id": "Y2lzY29z",
      "name": "Enterprise Edition",
      "totalUnits": 1000,
      "consumedUnits": 1
    },
    {
      "id": "MGUzZjBj",
      "name": "Messaging",
      "totalUnits": 1000,
      "consumedUnits": 0
    }
]   

But it doesn't work with the following json file:

{
  "items": [
    {
      "id": "Y2lzY29z",
      "name": "Enterprise Edition",
      "totalUnits": 1000,
      "consumedUnits": 1
    },
    {
      "id": "MGUzZjBj",
      "name": "Messaging",
      "totalUnits": 1000,
      "consumedUnits": 0
    }
  ]
}

I don't know how to write the query correctly

$query .= "INSERT INTO organizations
                    (id, displayName, created) 
            VALUES ('".$row["id"]."', '".$row["displayName"]."', 
                    '".$row["created"]."');

Thanks!

First you should parameterise the query and then bind the values, this protects against SQL Injection Attack .

This also allows you to prepare the query once but execute it, with different parameter many times, thus saving round trips to the database and multiple compilations of the query.

And of course the array starts from $array['items']

<?php
//Connect PHP to MySQL Database
$connect = mysqli_connect("localhost", "root", "pass", "dbname"); 

$filename = "organizations.json";
$data = file_get_contents($filename); //Read the JSON file in PHP
$array = json_decode($data, true); //Convert JSON String into PHP Array

//prepare the query once
$query = "INSERT INTO organizations
                    (id, displayName, created) 
            VALUES (?,?,?)"; 
$stmt = $connect->prepare($query);

foreach($array['items'] as $row) {
    $stmt->bind_param('iss',  $row['id'], $row['displayName'], $row['created']);
    $stmt->execute();

    $table_data .= "<tr>
            <td>$row[displayName]</td>
            <td>$row[created]</td>
        </tr>";
}

"it doesn't work with the following json file"

...that's because the structure is different in the JSON. This should be fairly obvious - you can't expect it to just automatically work with any arbitrary data structure you give it.

The code needs modifying to read the new structure. In this specific case it's quite trivial - you have an inner object holding the array, so you have to loop through that object instead of the top-level:

Change

foreach($array as $row)

to

foreach($array["items"] as $row)

Your second Json object has a field, "items". So you you just need to make a small adjustment to your code:

    <?php
         ...
          $array = json_decode($data, true); 
          $items = $array["items"];
          foreach($items as $row){
          ...
          }

With the same code, You just need to adjust in foreach loop. Use $array['items'] instand of just $array

  <?php
      $connect = mysqli_connect("localhost", "root", "pass", "dbname"); //Connect PHP to MySQL Database
      $query = '';
      $table_data = '';
      $filename = "organizations.json";
      $data = file_get_contents($filename); //Read the JSON file in PHP
      $array = json_decode($data, true); //Convert JSON String into PHP Array
      foreach($array['items'] as $row) //Extract the Array Values by using Foreach Loop - "Inserto todos los campos en la tabla pero no muestro el 'id' en la web"
      {
       $query .= "INSERT INTO organizations(id, displayName, created) VALUES ('".$row["id"]."', '".$row["displayName"]."', '".$row["created"]."'); ";  // Make Multiple Insert Query 
       $table_data .= '
            <tr>
        <td>'.$row["displayName"].'</td>
        <td>'.$row["created"].'</td>
    </tr>
       '; //Data for display on Web page
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM