2014-02-07 52 views
0

以下是我的代碼插入記錄到數據庫中使用JSON

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

新建JSON和PHP,請張貼任何變化,我可以做這些記錄插入到MySQL。

多虧了你們,我的第一個查詢得到有效解決。

然而,另一部分仍然存在。我想以字符串格式將json編碼的數據保存到mysql中。我怎麼能這樣做?

回答

0

使用$var如下,

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

注:Please, don't use mysql_* functions in new code。他們不再維護and are officially deprecated。請參閱red box?請改爲了解prepared statements,並使用PDOMySQLi - this article將幫助您決定哪個。如果您選擇PDO,here is a good tutorial

+0

你的意思'$ var當成$水果=> $ color'? –

+0

@UshakovNik - 是的,謝謝。糾正。 – Rikesh

+0

錯誤 - 解析錯誤:語法錯誤在第22行上 –

0

我想你沒有帶使用正確的變量在for循環。在json解碼之後,你在for循環中使用了相同的變量。 (你應該使用$ var而不是$ json)我猜。

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

錯誤 - 無法連接 - 事件插入失敗:查詢是空的 –

相關問題