无法使用PHP从JSON文件向MYSQL数据库添加数据

时间:2016-02-25 13:59:42

标签: php mysql json mysqli

我是PHP的新手。我现在几个小时都在努力完成这项任务。之前我使用json_encode将数据从MYSQL获取到JSON文件。现在我尝试将JSON文件中的相同数据添加到新的MYSQL数据库中。我有一个问题,在将数组传递给MYSQL数据库之前将数组转换为字符串。数据库工作,我能够添加"玩家"通过插入手动值而不是数组中的$值。我的代码如下所示:

<?php
//open connection to mysql db
$con = mysqli_connect("localhost","root","","scoreboard2") or die("Error " . mysqli_error($con));

$scorefile = file_get_contents('scores.json');
$Score = json_decode($scorefile, true);

echo '<pre>' . print_r($Score, true) . '</pre>';

foreach ($Score as $field => $value) {
    // Use $field and $value here

    print_r($field . '=>' . $value . '<br/>', true);

    //mysqli_query($con, "INSERT INTO scores (name, score, time) VALUES ($value->name, $value->score, $value->time)");
}

//mysqli_close($con);
?>

JSON文件如下所示:

[
 {"id":"22",
  "name":"Jack",
  "score":"2142",
  "time":"196:13",
  "ts":"2016-02-23 15:36:23",
  "date":"2016-02-23"},

 {"id":"23",
  "name":"Bob",
  "score":"7026",
  "time":"35:54",
  "ts":"2016-02-23 15:40:33"}
]

等......以及&#34;错误&#34;是这样的:

  

注意:第13行的F:\ XAMPP \ htdocs \ JSON_MySQL \ decode.php中的数组到字符串转换

2 个答案:

答案 0 :(得分:1)

您的问题是,您正在使用json_decode()的参数2将.json文件中的数据转换为数组{/ 1}}。

这是将您的对象转换为数组,因此您在此行中使用的语法是错误的

true

因为您使用的是对象表示法。

所以从

改变这一行
mysqli_query($con, "INSERT INTO scores 
                           (name, score, time) 
                    VALUES ($value->name, $value->score, $value->time)");

$Score = json_decode($scorefile, true);

SO

$Score = json_decode($scorefile);

另请注意,我使用单引号引用了值,并在?php $con = mysqli_connect("localhost","root","","scoreboard2") or die("Error " . mysqli_error($con)); $scorefile = file_get_contents('scores.json'); $Score = json_decode($scorefile); foreach ($Score as $object) { mysqli_query($con, "INSERT INTO scores (name, score, time) VALUES ('{$object->name}', '{$object->score}', '{$object->time}')"); } mysqli_close($con); ?> 中包装了对象属性,这在双引号文字中使用对象或数组表示法时是必需的。

答案 1 :(得分:1)

错误

  

注意:数组转换为字符串   第13行的F:\ XAMPP \ htdocs \ JSON_MySQL \ decode.php

由行

生成

print_r($field . '=>' . $value . '<br/>', true);

(实际上是第13行)

您尝试将$value数组(您的第二个得分对象)转换为字符串,以便将其与字符串的其余部分连接起来

请注意,如果您通过

替换错误生成行
echo '<pre>' .$field . '=>' . print_r($value, true) . '</pre>'.'<br/>';

你得到了

0=>Array
(
    [id] => 22
    [name] => Jack
    [score] => 2142
    [time] => 196:13
    [ts] => 2016-02-23 15:36:23
    [date] => 2016-02-23
)

1=>Array
(
    [id] => 23
    [name] => Bob
    [score] => 7026
    [time] => 35:54
    [ts] => 2016-02-23 15:40:33
)

您可能最初期望的