将JSON编码的数据插入MySQL [英] Inserting json encoded data into mysql

查看:113
本文介绍了将JSON编码的数据插入MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个后续问题,之前我已经 关于将json插入到mysql中.我再次对其进行编码,现在我希望将其打印回mysql.我不知道我应该如何将编码的json输出作为字符串打印回mysql中.以下是我当前的代码

This is a follow up question , earlier i had asked about inserting json into mysql . I encoded it again and now i want it to be printed back to mysql . I don't know how am i supposed to print the encoded json output as string back into mysql . Folowing is my current code

<?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());
    }
  //  }
?>

任何帮助将不胜感激.在此先感谢:)

Any help would be much appreciated .Thanks in advance :)

推荐答案

因为您有一个数组数组,所以正确的foreach看起来像这样:

Because you have an array of arrays, the correct foreach would look like this:

$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);

这篇关于将JSON编码的数据插入MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆