通过 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/