Home > Blockchain >  Can't Insert JSON Data into MySQL
Can't Insert JSON Data into MySQL

Time:11-18

I can't get the data in json format and insert it into mysql database.

I have this JSON format in employee_data.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
          $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

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

CodePudding user response:

you need to first get the correct objects before going through the foreach

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

or instead

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