用PHP解析JSON文件并插入SQL ----

时间:2018-07-23 15:42:51

标签: php sql json parsing insert

所以我一直在研究,似乎没有方法可以正确解析我的文件。我试过这两个代码,我的数据被插入到sql中,但是它被插入了3次,第一次插入是正确的,而其他2次是空白的。这是我的JSON文件和代码:

JSON:

   [
  {
    "Comments": {
      "Manufacturer": "--E", 
      "Model": "----- -----  ----", 
      "BIOSFamily": "---", 
      "BIOSDate": --/--/---8", 
      "SerialNumber": "---------"
    }
  }, 
   {
    "#ComputerSystem.v1-----------ystem": {
      "/redfish/v1/Systems/1/": {
        "AssetTag": "                                ", 
        "Bios": {
          "@odata.id": "/redfish/v1/systems/1/bios/"
            }, 
            "BiosVersion": "U----------------)", 
            "Boot": {
          "BootSourceOverrideMode": "-----y", 
          "BootSourceOverrideTarget": "None", 
          "BootSourceOverrideEnabled": "Disabled", 
          "BootSo-----------arget@Redfish.AllowableValues": [
            "None", 
            "Cd", 
            "Hdd", 
            "Usb", 
            "Utilities", 
           "Diags", 
           "BiosSetup", 
            "Pxe", 
           "UefiShell"
          ]

代码:

<?php

 $connect = mysqli_connect("reserve1", 
"root", "","server_31");

 $filename = "-----.json";

 $data = file_get_contents($filename);

 $array = json_decode($data, true);

 foreach($array as $row)
    {
  $sql = "INSERT INTO servers (Model, 
    Manufacturer, BIOSFamily, 
       BIOSDate, 
    SerialNumber)  VALUES 
    ('".$row["Comments"]["Model"]."' , 
    '".$row["Comments"] 
     ["Manufacturer"]."',
   '".$row["Comments"] 
  ["BIOSFamily"]."','".$row["Comments"] 
   ["BIOSDate"]."','".$row["Comments"] 
   ["SerialNumber"]."')";
        mysqli_query($connect, $sql);
       }




    echo "Data in";

   ?>

错误:“注意:未定义的索引:注释”

我尝试过的其他forloops是:

foreach($data as $Comments)
{
    $sql =" INSERT INTO 
'servers'('Manufacturer','Model', 
'BIOSFamily','BIOSDate', 
'SerialNumber'), VALUES('{$Comments- 
   >Manufacturer}', '{$Comments- 
   >Model}',  
    '{$Comments->BiosFamily}', 
    '{$Comments->BiosDate}',
                 '{$Comments- 
   >SerialNumber}')";

    }

错误:“注意:试图获取非对象的属性”

重申一下:第一种方法确实将我的信息保存到sql上,但是这样做了3次,最后2个条目为空白。第二种方法不会在我的表中插入任何内容。


编辑:

所以我尝试了vardump,使用文件本身,我得到的只是NULL,复制并粘贴内容,并在我得到的脚本中将其标记为$ json ='content'。

 C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:16:
array (size=1)
  0 => 
    object(stdClass)[1]
      public 'Comments' => 
        object(stdClass)[2]
         public 'Manufacturer' => string 'HPE' (length=3)
          public 'Model' => string '-------------' (length=20)
          public 'BIOSFamily' => string '---' (length=3)
          public 'BIOSDate' => string '--/--/----' (length=10)
          public 'SerialNumber' => string '-------' (length=10)
C:\Users\Administrator\Desktop\Reserve1\newtry\NEWJSONP.php:17:
array (size=1)
  0 => 
    array (size=1)
      'Comments' => 
        array (size=5)
          'Manufacturer' => string '---' (length=3)
          'Model' => string '------ ----------' (length=20)
          'BIOSFamily' => string '---' (length=3)
          'BIOSDate' => string '--/--/----' (length=10)
          'SerialNumber' => string '-------' (length=10)

1 个答案:

答案 0 :(得分:1)

由于{em> $ array 对象仅将 Comments 保持在第一位置,因此在foreach循环中只需索引第一项。从var_dump输出中看到0索引:

array (
  0 => 
  array (
    'Comments' => 
    array (
      'Manufacturer' => '--E',
      'Model' => '----- -----  ----',
      'BIOSFamily' => '---',
      'BIOSDate' => ' --/--/-- - 8 ',
      'SerialNumber' => '---------',
    ),
  ),
  1 => 
  array (
    '#ComputerSystem.v1-----------ystem' => 
  ...

因此,遍历 Comments 数组并使用参数化以提高可读性:

$connect = new mysqli($servername, $username, $password, $dbname);

// PREPARED STATEMENT
$sql = "INSERT INTO servers (Model, Manufacturer, BIOSFamily, BIOSDate, SerialNumber)
        VALUES(?, ?, ?, ?, ?)";

// INDEX FIRST ITEM AT 0
foreach($array[0] as $row) { 

    $stmt = $connect->prepare($sql);

    // BIND PARAMETERS (NO COMMENTS INDEX)
    $stmt->bind_param("sssss", $row["Model"], 
                               $row["Manufacturer"],
                               $row["BIOSFamily"],
                               $row["BIOSDate"],
                               $row["SerialNumber"]);

    // EXECUTE STATEMENT
    $result = $stmt->execute();    
}