du22399 2018-08-07 11:07
浏览 316

使用PHP将JSON数据保存到MySQL中

Im getting json data from another server and need thouse data to be saved on mysql.I tryed this code but theres a problem when i run this code i get : Illegal string offset for each VALUES. I hope I made things clear if there's anything I didn't explain please do tell.

    <?php
       require('db.php');
      $url = 'xxxxx';
        $data =json_encode(array('xxx' => 'xxxx',
            'xxxx' => 'xxxxx',
            'xxxx' =>'xxxx',
            'xxxx' =>'xxxx',
               'xxxx' =>'xxxx')
   );


   $options = array(
   'http' => array(
    'header'  => "Content-type: application/json",
    'method'  => 'POST',
    'content' => $data
  )  
   );
    $context= stream_context_create($options);
   $result = file_get_contents($url, false, $context);
  if ($result === FALSE) { }

   echo $result ;

  foreach ((array)$result as $row) {
   $table="INSERT INTO table_name(xxx,xxx,xx,xxx,xx,xxx,xxx,xxxx,xxx) 
    VALUES('".$row["xxxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxx"]."','".$row["xxxx"]."')";
   if ($conn->query($table ) === TRUE) {
  echo "Record added Successfully<br>";
   }
   else
  {
   echo "Error: " . $insert_value . "<br>" . $con->error;
 }
 }

  ?>
  • 写回答

1条回答 默认 最新

  • dongsong73032 2018-08-07 11:12
    关注

    There should be else statement as well with if conditions, in case there are results. And the results should be parsed in else.

    The code should be :

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE) {
        echo "Error in fetching records.";
    } else {
        echo $result;
        $rows = (array) $result;
        foreach ($rows as $row) {
            $table = "INSERT INTO table_name(xxx,xxx,xx,xxx,xx,xxx,xxx,xxxx,xxx) 
        VALUES('" . $row["xxxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxx"] . "','" . $row["xxxx"] . "')";
            if ($conn->query($table) === TRUE) {
                echo "Record added Successfully<br>";
            } else {
                echo "Error: " . $insert_value . "<br>" . $con->error;
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂