dongqiong8021 2018-10-24 14:00
浏览 242
已采纳

将JSON数组插入MySQL数据库不能正确循环

I am trying to insert some data from a JSON file into a SQL database.

I have written this script to reads the JSON, decodes it and inserts it, however I am only getting the first JSON line as I don't think it is looping properly.

I am also getting a duplicate error, which I believe is caused as the code is trying to loop the same line, not the next line in the JSON! (Only the first JSON item inserts)

How do I get my script to loop each line in my JSON and insert it?

Thanks!

Code I am working with:

<?php
error_reporting(E_ALL);
$root = $_SERVER['DOCUMENT_ROOT'];
require ($root."/config.php");

$json = file_get_contents('propertiesA.json');
$obj = json_decode($json,true);

foreach($obj as $item) {
    $query =  "INSERT INTO unverified_list (
         title,
         street_address,
         locality
       ) VALUES (
         '".$item['title']."',
         '".$item['street_address']."',
         '".$item['locality']."'

       )"; 
}

$result = $link->query($query);

if ($link->query($query) === TRUE) {
    echo "Property Added";
} else  {
  echo "Error: " . $query . "<br>" . $link->error;
}

mysqli_close($link);

?>
  • 写回答

1条回答 默认 最新

  • donglu8334 2018-10-24 14:03
    关注

    The problem is that you only execute the query after the loop has finished, you need to run it on each line...

    foreach($obj as $item) {
           $query =  "INSERT INTO unverified_list (
             title,
             street_address,
             locality
           ) VALUES (
             '".$item['title']."',
             '".$item['street_address']."',
             '".$item['locality']."'
    
           )"; // Remove } from here to after next bit of code
    
           $result = $link->query($query);
    
           if ($link->query($query) === TRUE) {
               echo "Property Added";
           } else  {
               echo "Error: " . $query . "<br>" . $link->error;
           }
    }
    

    Although this will now give you a message for each row inserted.

    You should also look into using prepared statements which will protect you from all sorts of potential issues.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java map类型数据格式,如何快速通过前缀匹配元素
  • ¥15 stc12c5a60s2、QMC5883L、LCD1602组合测量磁场所需程序
  • ¥15 vba参数转c++ SAFEARRAY
  • ¥20 Win11测试yolov4,“找不到nvcuda.dll”怎么办?
  • ¥15 simulink绘制bode图
  • ¥15 php_network_getaddresses: getaddrinfo failed: Name or service not known
  • ¥15 用msg发消息出现的问题
  • ¥15 unity3d机械臂
  • ¥20 判断两个表是否完全相同
  • ¥20 工控机出现散热器转一下停一下这种情况,是什么原因造成的