php - 如何通过 PHP 将 JSON 对象数组添加到 MySQL 中

标签 php mysql json

通过 PHP 将 JSON 元素数组添加到 MySql 时遇到问题。 这是数组的片段:

[{ "title": "Wilfred", "year": "2011–2014", "released": "23 Jun 2011", "runtime": "30 min", "genre": "Comedy", "director": "N/A", "actors": "Elijah Wood, Jason Gann, Fiona Gubelmann, Dorian Brown", "imdbRating": "7.9" },
{ "title": "otherMovie", "year": "2012", "released": "23 Jun 2011", "runtime": "30 min", "genre": "Comedy", "director": "N/A", "actors": "Elijah Wood, Jason Gann, Fiona Gubelmann, Dorian Brown", "imdbRating": "7.9" }]

所以是的,我只想将所有这些添加到 MySQL 的表中。 表已经制作好了,列也已经制作好了 - 我只是无法将数据放入其中。 这是我的 PHP 代码:

<?php
$servername = "localhost";
$username = "me";
$password = "pw";


$con=mysqli_connect($servername, $username, $password, "movies");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }


mysqli_close($con);


$jsondata = file_get_contents('rdymovies.json');
$data = json_decode($jsondata);

// remove the ,true so the data is not all converted to arrays
// Now process the array of objects

//title, year, released, runtime, genre, director, actors, imdbRating
foreach ( $data as $movdata ) {
    $title = $movdata->title;
    $year =     $movdata->year; 
    $released =    $movdata->released;
    $runtime =      $movdata->runtime;
    $genre = $movdata->genre;
    $director =       $movdata->director;
    $actors = $movdata->actors;
    $imdbRating = $movdata->imdbRating;
    $sql = "INSERT INTO movies 
             (title, year, released, runtime, genre, director, actors,     imdbRating) 
            VALUES
             ('$title','$year','$released','$runtime',
              '$genre','$director','$actors','$imdbRating')";
    $res = mysqli_query($sql,$con);
echo $res;
    if(!$res){
        $result = new stdClass();
        $result->status = false;
        $result->msg = mysql_error();
        echo json_encode($result);
        exit;
    }
}

?>

最佳答案

<强> mysqli_query() 期望参数 1 为 mysqli。您将查询(字符串)作为第一个参数传递。 更改mysqli_query($sql,$con)mysqli_query($con, $sql)

关于php - 如何通过 PHP 将 JSON 对象数组添加到 MySQL 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820296/

相关文章:

php - preg_replace 正则表达式模式

php - 在 SQL 中有效但在 PHP 中无效的查询

mysql - 从两个连接表更新单个表 (SQL)

php - 将mysql数据拉入多维数组

ios - JSON 到自定义对象数组 (Swift)

php - YouTube Api : snippet. live_chat_id 是必需的

php获取数组的数据大小

PHP SQL 查询错误 - WHERE 子句中未知的数组列

python - zabbix api获取当前时间24小时前的项目值

javascript - 如何正确地将 C# 对象列表解析为 Javascript。仅显示类似 "System.Collections.Generic.List` 1"的类型