在通过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;
}
}
?>
答案 0 :(得分:1)
mysqli_query()
期望参数1为mysqli。您将查询(String)作为第一个参数传递。
将mysqli_query($sql,$con)
更改为mysqli_query($con, $sql)
答案 1 :(得分:0)
从顶部删除mysqli_close($con)
。
将mysqli_query($sql,$con)
更改为mysqli_query($con, $sql)
它应该工作。