【问题标题】:Inserting record into database using JSON使用 JSON 将记录插入数据库
【发布时间】:2014-02-07 08:39:49
【问题描述】:

以下是我的代码

<?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 中。我该怎么做?

【问题讨论】:

    标签: php mysql json


    【解决方案1】:

    如下使用$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

    【讨论】:

    • 你的意思是$var as $fruit =&gt; $color
    • 错误 - 解析错误:语法错误,第 22 行的 simple.php 中出现意外的 'mysql_query' (T_STRING)
    • 除了包含 2 个字段、fruit 和 color 的 db 之外,没有其他内容。
    • 它正在将空字段传递给 db ,n dis 即将到来 - 注意:未定义的变量:第 21 行 /opt/lampp/htdocs/example/simple1.php 中的水果 注意:未定义的变量:在第 21 行的 /opt/lampp/htdocs/example/simple1.php 中着色
    • 你确定你改变了我提到的 foreach 吗?
    【解决方案2】:

    我认为您没有在 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());
        }
        }
    ?>
    

    【讨论】:

    • 错误 - 无法连接 - 事件插入失败:查询为空
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2017-09-22
    相关资源
    最近更新 更多