这是一个后续问题,早些时候我有asked 关于将json插入mysql。我再次对其进行编码,现在我想将它打印回mysql。我不知道我应该如何将编码的json输出作为字符串打印回mysql。 Folowing是我目前的代码
<?php
$json = array
(
array("pineapple","yellow"),
array("watermelon","red"),
array("orange","orange")
);
var_dump($json);
var_dump(json_decode($json, true));
$newelements = json_encode( $json, JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE );
echo $newelements;
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db("json",$dbhandle)
or die("Could not select json");
// foreach ($enc as $fruit => $color) {
$db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES('$fruit','$color')");
mysql_query($db_insert);
if (!$db_insert)
{
die('Could not connect - event insert failed: ' . mysql_error());
}
// }
?>
任何帮助都会非常感激。谢谢提前:)
答案 0 :(得分:-1)
因为你有一个数组数组,正确的foreach
看起来像这样:
$values = array();
foreach ($newelement as $element) {
$values[] = "('".mysql_real_escape_string($element[0])."','".mysql_real_escape_string($element[1])."')";
}
$db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES ".implode(",", $values);