使用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.
New to JSON and PHP, please post any changes I can do to insert those records into MySQL.
但是,还有一部分.我想将JSON编码数据以字符串格式保存到MySQL中.我该怎么办?
However, another part remains. I want to save the JSON encoded data into MySQL in string format. How can I do so?
答
按如下所示使用$var
,
foreach ($var as $fruit => $color) {
$db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES ('$fruit','$color')");
.....
注意: 请不要在新代码中使用mysql_*
函数 > .它们已不再维护并已正式弃用.看到 红色框 ?了解有关 准备好的语句 的信息,并使用 MySQLi -本文将帮助您确定哪一个.如果您选择PDO,这里是一个很好的教程.
Note: Please, don't use mysql_*
functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.