如何将json值插入mysql数据库

时间:2015-06-20 12:46:52

标签: php mysql json

我从网站上收到了这个JSON

https://openexchangerates.org/api/latest.json?app_id=1d85872a9b324abcabb2aea5ab397605 

它看起来像这样。

{
  "disclaimer": "Exchange rates...",
  "license": "Data sourced from various providers...",
  "timestamp": 1433782861,
  "base": "USD",
  "rates":
  {
      "BWP": 10.075038,
      "CHF": 0.934077,
      "CNY": 6.188018,
      "EUR": 0.890331,
      "GBP": 0.653896,
      "ZMW": 7.248788
   }
}

如何使用具有此结构的PHP,MySQL替换以前的值来插入或更确定地更新MySQL数据库。

CREATE TABLE IF NOT EXISTS `rate` (
  `currency_` varchar(10) NOT NULL Primary key,
  `value_` decimal(10,5) NOT NULL
)

2 个答案:

答案 0 :(得分:2)

您似乎想要填写字段currency_和字段value_。使用您发布的JSON并假设,$db是MySQLi连接链接:

$json = json_decode($result, true);
foreach($json['rates'] as $k => $v){
    $db->query("DELETE FROM `rate` WHERE `currency_` = '" . $db->real_escape_string($k) . "'");
    $db->query("INSERT INTO `rate` (`currency_`, `value_`) VALUES ('" . $db->real_escape_string($k) . "', " . floatval($v) . ")");
}

如果您只想将数组保存在数据库中,可以将其保存为JSON或者可以将其序列化:

$arr = serialize(json_decode($result, true));

只需更新:

$json = json_decode($result, true);
foreach($json['rates'] as $k => $v)
    $db->query("UPDATE `rate` SET `value_` = " . floatval($v) . " WHERE `currency_` = '" . $db->real_escape_string($k) . "'");

答案 1 :(得分:-1)

<?php
include('con.php'); //http://www.w3schools.com/php/func_mysqli_connect.asp

//get the json
$json = file_get_contents('https://openexchangerates.org/api/latest.json?app_id=1d85872a9b324abcabb2aea5ab397605');

//decode json, in to an array
$decoded = json_decode($json, true);

//iterate over the array
foreach($decoded['rates'] as $currency => $rate){
    $rates[] = "('" . $currency . "', '" . $rate . "')";
}

//query, just connect once
 $sql =  "INSERT INTO `lol`.`rate` (`currency_`, `value_`) VALUES " . implode(",",$rates) . "ON DUPLICATE KEY UPDATE value_ = VALUES(value_)";

if (mysqli_query($con, $sql)) {
    echo 'Record created successfully<br>';
} else {
    echo $sql . '"<br>"' . mysqli_error($con);
};    
?>

编辑:http://www.w3schools.com/php/func_mysqli_connect.asp

con.php:

<?php
//use your connection data here
$user = "";
$pass = "";
$host = "";
$dbdb = "";

$con = mysqli_connect($host, $user, $pass, $dbdb);

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}