简体   繁体   中英

Inserting json encoded data into 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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM