I'm trying to insert nested JSON data received from tmdb API into my mySQL database.
I know how to insert an nested JSON already, but since the new record that I need to create will have many to many relation (movie and movie genres) I'm assuming I have to insert multiple rows with of the same data with different Movie genres.
I've been trying to use another foreach loop for movie genre with no success. I would really appreciate some help.
<?php
$api = "https://api.themoviedb.org/3/movie/popular?api_key=<<api-key>>&language=en-US&page=1";
$jsondata = file_get_contents($api);
//now you have result as associative array
$data = json_decode($jsondata, true);
$array_data = $data['results'];
$array_genre= $data['results']['genre'];//
include "indexmoviedb.php";
$stmt=$db->prepare("INSERT INTO movie VALUES(:title,:poster_path,:backdrop_path,:rating,:overview,:genre)");
foreach($array_data as $row){
foreach ($array_genre as $genrerow) {// I'm assuming I have to do something like this
$stmt->bindParam(":title",$row['title'] );
$stmt->bindParam(":poster_path",$row['poster_path'] );
$stmt->bindParam(":backdrop_path",$row['backdrop_path'] );
$stmt->bindParam(":rating",$row['vote_average'] );
$stmt->bindParam(":overview",$row['overview'] );
$stmt->bindParam(":genre",$row['genres_ids'][] );// what goes in here?
$stmt->execute();
}
}
?>
this is the json file that I'm trying to insert
{
"results": [{
"id": 351286,
"vote_average": 6.6,
"title": "Jurassic World: Fallen Kingdom",
"popularity": 228.669,
"poster_path": "/c9XxwwhPHdaImA2f1WEfEsbhaFB.jpg",
"genre_ids": [
28,
12,
878
],
"backdrop_path": "/gBmrsugfWpiXRh13Vo3j0WW55qD.jpg"
}]
}
$data['results']['genre']to$data['results'][0]['genre']