使用JSON将记录插入数据库 [英] Inserting record into database using JSON

查看:499
本文介绍了使用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.

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

但是,还有一部分.我想将JSON编码数据以字符串格式保存到MySQL中.我该怎么办?

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

推荐答案

按如下所示使用$var

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

注意: 请不要在新代码中使用mysql_*函数 > .它们已不再维护并已正式弃用.看到 红色框 ?了解有关 准备好的语句 的信息,并使用 MySQLi -本文将帮助您确定哪一个.如果您选择PDO,这里是一个很好的教程.

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.

这篇关于使用JSON将记录插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆