gpt4 book ai didi

php 和 mysql db 从 Json 文件插入

转载 作者:行者123 更新时间:2023-11-29 12:13:09 25 4
gpt4 key购买 nike

正如你们中的一些人建议的那样,我正在尝试自动将 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 object

含义:您必须循环遍历各个国家/地区或获取第一个国家/地区。

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;
}
}

关于php 和 mysql db 从 Json 文件插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30315160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com