简体   繁体   English

无法将 JSON 数据插入 MySQL

[英]Can't Insert JSON Data into MySQL

I can't get the data in json format and insert it into mysql database.我无法获取 json 格式的数据并将其插入到 mysql 数据库中。

I have this JSON format in employee_data.json我在 employee_data.json 中有这个 JSON 格式

{
   "MessageCode":"00",
   "Message":[
      {
         "name":"Michael Bruce",
         "gender":"Male",
         "designation":"System Architect"
      },
      {
         "name":"Jennifer Winters",
         "gender":"Female",
         "designation":"Senior Programmer"
      }
   ]
}

Here is my PHP code这是我的 PHP 代码

<?php
          $connect = ysqli_connect("localhost", "root", "", "test");
          $query = '';
          $table_data = '';
          $filename = "employee_data.json";
          $data = file_get_contents($filename); 
          $array = json_decode($data, true); 
          foreach($array as $row) 
          {
           $query .= "INSERT INTO tbl_employee(name, gender, designation) 
           VALUES ('".$row["name"]."', 
                   '".$row["gender"]."', 
                   '".$row["designation"]."'); ";
          }
          ?>
    

How to $data return only如何 $data 只返回

[
   {
      "name":"Michael Bruce",
      "gender":"Male",
      "designation":"System Architect"
   },
   {
      "name":"Jennifer Winters",
      "gender":"Female",
      "designation":"Senior Programmer"
   }
]

you need to first get the correct objects before going through the foreach在通过 foreach 之前,您需要先获取正确的对象

$array = json_decode($data, true); 
          $array = $array['message'];
          foreach($array as $row) {}
      

or instead或者相反

foreach($array['message'] as $row) {}

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

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