簡體   English   中英

使用JSON將記錄插入數據庫

[英]Inserting record into database using 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中。 我該怎么辦?

我認為您沒有在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());
    }
    }
?>

使用$var如下

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

注意: 請不要在新代碼中使用mysql_*函數 它們不再維護,已正式棄用 看到紅色框了嗎? 而是了解准備好的語句 ,並使用PDOMySQLi- 本文將幫助您確定哪一個。 如果您選擇PDO, 這是一個很好的教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM