[英]Inserting record into database using 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中。 我該怎么辦?
我認為您沒有在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());
}
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.