Scriptomaniac
Scriptomaniac

Reputation: 232

How to add an array of JSON objects into MySQL via PHP

Having problems adding my array of JSON elements into MySql via PHP. Here is a snippet of the array:

[{ "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" }]

So yeah, I just want to add all of that into a table in MySQL. The table is already made, as are the columns - I just can't get the data into it. Here is my PHP code:

<?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;
    }
}

?>

Upvotes: 0

Views: 197

Answers (2)

Remove mysqli_close($con) from the top. Change mysqli_query($sql,$con) to mysqli_query($con, $sql)

It should work then.

Upvotes: 0

Mujahidh
Mujahidh

Reputation: 458

mysqli_query() expects parameter 1 to be mysqli. You are passing the query(String) as first parameter. Change the mysqli_query($sql,$con) to mysqli_query($con, $sql)

Upvotes: 1

Related Questions