gpt4 book ai didi

php - 使用 JSON 将记录插入数据库

转载 作者:行者123 更新时间:2023-11-30 00:42:56 26 4
gpt4 key购买 nike

以下是我的代码

<?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中。我怎样才能这样做?

最佳答案

使用 $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相反,并使用 PDO ,或MySQLi -this article将帮助您决定哪个。如果您选择 PDO,here is a good tutorial .

关于php - 使用 JSON 将记录插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21622946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com