将数据从外部json附加到mysql表

时间:2013-10-09 02:34:45

标签: php mysql json

我试图将外部json中的数据附加到另一个MYSQL表中。我熟悉PHP但不是任何形状或形式的专业人士。因此,如果我犯了一些愚蠢的错误,我就不会感到惊讶。

这就是我正在做的事情

<?php
// Declaring database parameters as constants
define('DB_NAME', 'this has my db name');
define('DB_USER', 'this stores my user name');
define('DB_PASSWORD', 'my password');
define('DB_HOST', 'localhost');

$data_variable = file_get_contents("http://data.cityofnewyork.us/resource/a7hj-s5px.json");

//making database connection
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

//Checking for server connection and printing statements

if(!$link){
    die('could not connect:' . mysql_error());
}

$db_selct = mysql_select_db(DB_NAME, $link);

if(!$db_selct){
    die('Can not use : ' . DB_NAME . ':' .mysql_error());
}

//echo 'connection sucessful';

$data = json_decode($data_variable, true);

//Let me know I can turn this on to show how the array looks like.
//print_r(array_values($data));

foreach($date["noise"] as $new_data){

$var_one = $new_data[incident_zip];

mysql_query("INSERT INTO noise (zip_code) VALUES('$var_one')") or die (mysql_error());
}


?>

我做错了什么?

我在这里找到了一个非常类似的解决方案并且几乎遵循它但我可能没有做正确的事情

JSON to MYSQL - is JSON response formatted correctly - looping properly?

以下是我看到错误消息的页面的链接 http://soumghosh.com/otherProjects/phpDataOperation/test1.php

错误
警告:在第31行的/home3/soum/public_html/otherProjects/phpDataOperation/test1.php中为foreach()提供的参数无效

这仍处于调查阶段。我可能会回到这个问题,在建筑层面上寻求你们更多的意见。

1 个答案:

答案 0 :(得分:1)

您可以将foreach()块更改为以下内容,以避免出现警告和错误

if(isset($data)) {
    foreach($data as $new_data){
        $var_one = $new_data['incident_zip'];
        mysql_query("INSERT INTO noise (zip_code) VALUES('$var_one')") or die (mysql_error());
    }
} else {
  //log the error
}
相关问题