0

Following is my code

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

New to JSON and PHP, please post any changes I can do to insert those records into MySQL.

However, another part remains. I want to save the JSON encoded data into MySQL in string format. How can I do so?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Caffeine Coder
  • 1,869
  • 1
  • 17
  • 35

2 Answers2

0

I think you havn't used the correct variable in the for loop. After json decode you used the same variable in the for loop. (you should use $var instead of $json) i guess.

<?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());
    }
    }
?>
shanavascet
  • 589
  • 1
  • 4
  • 18
0

Use $var as below,

foreach ($var as $fruit => $color) {
    $db_insert = mysql_query("INSERT INTO fruits (fruit,color) VALUES ('$fruit','$color')");
    .....

Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Rikesh
  • 26,156
  • 14
  • 79
  • 87