使用php将json数据插入mysql数据库 [英] Insert json data into mysql database using php

查看:114
本文介绍了使用php将json数据插入mysql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从 json 文件发送到 mysql 数据库.我首先将数据放入一个数组,然后发送到一个 sql 查询,但我在使其正常工作时遇到了一些问题.这是我的代码.

I am trying to send data from a json file to a mysql database. I am first putting the data into an array and then sending to a sql Query but I am having some trouble making it work correctly. Here is my code.

$connect=mysql_connect('localhost', 'username', 'password');

IF (!$connect){
die ('Failed Connecting to Database: ' . mysql_error());}

  $json = file_get_contents('file.json');
  $data= json_decode($json);

  $array=array();


  foreach ($data->data->children as $postdata){
      $array['url'] = $postdata->data->url;
      $array['id'] = $postdata->data->id;

  };

  $columns = implode(",",  array_keys($array));
  $escaped_values = array_map('escape_string', array_values($array));
  $values = implode(", ", $escaped_values);
  $QUERY = "IF (EXISTS(SELECT * FROM mytable) IS NOT NULL)
            TRUNCATE TABLE mytable;

      INSERT INTO mytable ($columns) VALUES ($values)";

  mysql_query($QUERY);

  mysql_close($connect);

'我对此很陌生,所以这可能是完全错误的,但我想知道这是否存在问题,或者是否有更有效的方法来做到这一点.

' I am pretty new at this so this could be completely wrong but I was wondering if there are problems with this, or if there is a more efficient way to go about doing this.

推荐答案

来自 手册:

mysql_query() 发送一个唯一的查询(多个查询不是支持)到当前活动的数据库

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database

您在 1 个呼叫中发送了 2 个查询,但不受支持.

You are sending 2 queries in 1 call and that is not supported.

这篇关于使用php将json数据插入mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆