这是一个后续问题,之前我在asked上讨论了如何将json插入到mysql中。我再次对其进行了编码,现在我希望将其打印回mysql。我不知道如何将编码后的json输出作为字符串打印回mysql。下面是我当前的代码
<?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());
    }
  //  }
?>如果有任何帮助,我们将不胜感激,请提前使用.Thanks :)
发布于 2014-02-07 22:34:59
因为您有一个数组数组,所以正确的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);https://stackoverflow.com/questions/21629922
复制相似问题