简体   繁体   English

如何从 JSON 中提取数据并将其插入 MySQL 与 PHP?

[英]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.我需要从 JSON 文件中提取数据并将其插入 MySQL 和 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:该代码适用于以下 json 文件:

[
    {
      "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:但它不适用于以下 json 文件:

{
  "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 .首先你应该参数化查询然后绑定值,这样可以防止SQL 注入攻击

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']当然,数组从$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" “它不适用于以下 json 文件”

...that's because the structure is different in the JSON. ...那是因为 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:在这种特定情况下,它非常简单——你有一个内部的 object 保存数组,所以你必须循环遍历那个 object 而不是顶层:

Change改变

foreach($array as $row)

to

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

Your second Json object has a field, "items".您的第二个 Json object 有一个字段“项目”。 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.使用相同的代码,您只需要在 foreach 循环中进行调整。 Use $array['items'] instand of just $array使用$array['items']代替$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
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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