使用JSON将记录插入数据库

时间:2014-02-07 08:39:49

标签: php mysql json

以下是我的代码

<?php
$json = '{"apples":"green","bananas":"yellow"}';
$var=(json_decode($json, true));
print_r($var);

$username = "root";
$password = "";
$hostname = "localhost"; 

//connection to the eventbase
$dbhandle = mysql_connect($hostname, $username, $password) 
  or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a eventbase to work with
$selected = mysql_select_db("json",$dbhandle) 
  or die("Could not select json");

// Insert $event array into eventbase
    foreach ($json as $key => $value) {
    $db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES" . $value);
    mysql_query($db_insert);
    if (!$db_insert)
    {
    die('Could not connect - event insert failed: ' . mysql_error());
    }
    }
?>

JSON和PHP新手,请发布我可以做的任何更改,将这些记录插入MySQL。

然而,另一部分仍然存在。我想以字符串格式将JSON编码数据保存到MySQL中。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

我认为你没有在for循环中使用正确的变量。在json解码之后,你在for循环中使用了相同的变量。 (你应该使用$ var而不是$ json)我猜。

<?php
$json = '{"apples":"green","bananas":"yellow"}';
$var=(json_decode($json, true));
//print_r($var);

$username = "root";
$password = "";
$hostname = "localhost"; 

//connection to the eventbase
$dbhandle = mysql_connect($hostname, $username, $password) 
  or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a eventbase to work with
$selected = mysql_select_db("json",$dbhandle) 
  or die("Could not select json");

// Insert $event array into eventbase
    foreach ($var as $key => $value) {
    $db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES" . $value);
    mysql_query($db_insert);
    if (!$db_insert)
    {
    die('Could not connect - event insert failed: ' . mysql_error());
    }
    }
?>

答案 1 :(得分:0)

使用$var,如下所示

foreach ($var as $fruit => $color) {
    $db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES ('$fruit','$color')");
    .....

注意: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial