php& mysql db从Json文件插入

时间:2015-05-19 01:04:38

标签: php mysql json insert

正如你们中的一些人建议的那样,我试图自动将mysql链接到json源并更新数据库。

所以我创建了我的php文件来插入数据。 我不知道为什么它不在这里编写代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="table-db.css" rel="stylesheet" type="text/css">
<title>Monetary Marker 12h update</title>
</head>

<body>
<?php
//connect to mysql db
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "my_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br />";


// NAME funzione
insertData:
//VALUES from JSON
$jsondata = file_get_contents('exchanges.json');
$data = json_decode($jsondata, true);

//convert json object to php associative array
$countryID = $data['country']['id'];
$countryName = $data['country']['name'];
$countryCurrency = $data['country']['currency'];
$buyRate = $data['country']['buy_rate'];
$sellRate = $data['country']['sell_rate'];

//VALUES DATE&HOUR
date_default_timezone_set('UTC+1');
$timestamp = date('Y-m-d H:i:s');

$spreadBuySell = (1/$buyRate)-$sellRate;

foreach($data as $item) {   
$sqlinsert = ("INSERT INTO MonetaryExchange12h   (countryID,countryName,countryCurrency,buyRate,sellRate,BuySellSpread,saveDateTime) 
VALUES    ('".$item['$countryID']."','".$item['$countryName']."','".$item['$countryCurrency']."','".$item['$buyRate']."','".$item['$sellRate']."','".$item['$spreadBuySell']."','".$item['$timestamp']."')");
    }

if ($conn->query($sqlinsert) === TRUE) {
echo "New record created successfully <br />";
} else {
echo "Error: " . $sqlinsert . "<br>" . $conn->error;
};
$conn->close();
?> 

<?php
// TABLE SHOW TEST
//connect to mysql db
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "mydb";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br />";

$sql = "SELECT   countryID,countryName,countryCurrency,buyRate,sellRate,BuySellSpread,saveDa teTime FROM MonetaryExchange12h ORDER BY ID DESC";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
echo '<tr><th>Country ID</th><th>Country</th><th>Currency</th><th>buy  Rate</th><th>sell Rate</th><th>Spread</th><th>Time Record</th></tr>';
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<tr><td>".$row["countryID"]."</td><td>".$row["countryName"]."</td><td>".$row["countryCurrency"]."</td><td>".$row["buyRate"]."</td><td>".$row["sellRate"]."</td><td>".$row["BuySellSpread"]."</td><td>".$row["saveDateTime"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
};
$conn->close();
?>

</body>
</html>

这是我的json文件的一部分:

{"country": [{"id":24,"name":"Argentina","currency":"ARS","buy_rate":0.046,"sell_rate": 30.8747}, {"id":35,"name":"Australia","currency":"AUD","buy_rate":0.0799,"sell_rate": 99.5156},{"id":13,"name":"Bosnia and  Herzegovina","currency":"BAM","buy_rate":0.0788,"sell_rate":20.4999}],"load":0.59583497047424}

你能告诉我哪里错了吗?

第一次更新

首先回答这个问题。我测试了代码,但它只返回1个条目,更准确地说是最后一个条目。我错过了什么?

 $jsondata = file_get_contents('exchanges.json');
 $data = json_decode($jsondata, true);
 foreach($data['country'] as $item) {
 $sqlinsert = "INSERT INTO MonetaryExchange12h   (countryID,countryName,countryCurrency,buyRate,sellRate) VALUES ('{$item['id']}','{$item['name']}','{$item['currency']}','{$item['buy_rate']}','{$item['sell_rate']}')";

2 个答案:

答案 0 :(得分:1)

如果您有错误报告,您会看到解码的json数组是一个关联数组。所以你的代码不起作用。

ini_set('display_errors', 1);
error_reporting(-1);

json object

含义:您必须遍历这些国家或获取第一个国家。

foreach($data['country'] as $country) {
    $countryID = $country['id'];
    //...add the rest
}

或者只是只做第一个元素:

$countryID = $data['country'][0]['id'];
//...add the rest.

备注

  • 当您过早关闭$sqlinsert时,您也会覆盖foreach变量。所以它只会输入最后的值。
  • 您正在冗余地设置变量$countryID / $countryName / ..等等,您应该将foreach循环更改为以下内容:
foreach($data['country'] as $item) {
    $sqlinsert = "INSERT INTO table (column,.....) VALUES ('{$item['id']}',...)";
    if ($conn->query($sqlinsert) === TRUE) {
        echo "New record created successfully <br />";
    } else {
        echo "Error: " . $sqlinsert . "<br>" . $conn->error;
    }
}

答案 1 :(得分:0)

好吧,我终于做到了。 谢谢你的帮助。

最终代码是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="table-db.css" rel="stylesheet" type="text/css">
<title>Monetary Marker 12h update</title>
</head>

<body>

<?php

//check errors
ini_set('display_errors', 1);
error_reporting(-1);

//connect to mysql db
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "my_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br />";


// NOME funzione
insertData:

$url = "http://esimeconomytools.altervista.org/monetarymarket/exchanges.json";
$json = file_get_contents($url);
$out = json_decode($json, true);
$dataCountry = $out['country'];
//$idCountry = $out['country']['id'];

foreach($dataCountry as $country) { 
$idCountry = addslashes($country['id']); 
$nameCountry = addslashes($country['name']); 
$Currency = addslashes($country['currency']);
$buyRate = addslashes($country['buy_rate']);
$sellRate = addslashes($country['sell_rate']);


$sqlinsert = "INSERT INTO MonetaryExchange12h    (countryID,countryName,countryCurrency,buyRate,sellRate) VALUES  ('$idCountry','$nameCountry','$Currency','$buyRate','$sellRate')";

if ($conn->query($sqlinsert) === TRUE) {
echo "New record created successfully <br />";
} else {
echo "Error: " . $sqlinsert . "<br>" . $conn->error;
}};
$conn->close();
?> 

要特别注意你放在哪里&#34 ;;&#34;在INSERT INTO命令结束时。 在那里,它将结束剧本的活动。

因此,如果你正在使用&#34; foreach&#34;,你将不得不放置&#34 ;;&#34;在函数的最后,或者在第一次(或最后一次)插入后中断循环。

大家好。 如果你们中的任何人都有一个链接到PHP的跨域JSON数据检索的好教程,欢迎。

阿尔贝托