繁体   English   中英

PHP和MySQL数据库从Json文件插入

[英]php & mysql db insert from Json file

正如您中某些人所建议的那样,我正在尝试自动将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']}')";

如果您有错误报告,您会看到解码的json数组是一个关联数组。 因此您的代码将无法正常工作。

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

json对象

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

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

或仅执行第一个元素:

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

笔记

  • 在过早关闭foreach同时,您还将覆盖$sqlinsert变量。因此,它只会输入最后一个值。
  • 您多余地设置了变量$countryID / $countryName /..etc,您应该将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;
    }
}

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

最终的代码是:

<!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();
?> 

请特别注意在何处放置“;” 在INSERT INTO命令的末尾。 在那里,它将结束脚本的活动。

因此,如果您使用“ foreach”,则必须输入“;”。 在函数的最后,否则您将在第一次(或最后一次)插入后中断循环。

谢谢大家。 如果您中的任何人都有指向php跨域JSON数据检索的好教程的链接,欢迎使用。

阿尔贝托

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM