user2363025
user2363025

Reputation: 6505

Inset php json encoded array into database

I need to insert elements of a php encoded array into a database and I'm completely stuck. I have first used json encode to to grab data from the database using an SQL query (which I did successfully) but I now need to be able to do the opposite. If anyone could help I'd greatly appreciate it. It's my second day of work and I'm not doing so well. The following is my code:

    $UserCoords_Query  = "Select Accuracy, Longitude, Latitude, Timestamp                            
        FROM UserDetails
          WHERE UserId =" . $UserID;
                  $UserCoords_result = mysql_query($UserCoords_Query);

if (mysql_num_rows($UserCoords_result) == 0) {
    echo "There are no users with an id of ". $UserID;
}

else {
            $EmptyArray=array();
    while ($row = mysql_fetch_array($UserCoords_result)) {
        $Accuracy=$row['Accuracy'];
        $Longitude= $row['Longitude'];
        $Latitude=$row['Latitude'];
        $Timestamp= $row['Timestamp'];

        $Queue= array('Accuracy:' => $Accuracy, 'Latitude' => $Latitude, 'Longitude' => $Longitude, 'Timestamp' => $Timestamp); 
        array_unshift($EmptyArray,$Queue);
}   

    $ObjectResponse = array('Coords' => $EmptyArray);
    echo json_encode($ObjectResponse);

    $Json_Encoded= json_encode($ObjectResponse);

   $Json_Decoded= json_decode($Json_Encoded, true);

    $Update_Query= "INSERT INTO UserDetails (UserId, Accuracy, Latitude, Longitude,         Timestamp)
    VALUES ('".$UserID."','".$Json_Decoded[0]        ['Accuracy']."','".$Json_Decoded[0]['Latitude']."',
    '".$Json_Decoded[0]['Longitude']."','".$Json_Decoded[0]['Timestamp']."')";

    mysql_query($Update_Query) or die(mysql_error());

Upvotes: 2

Views: 1309

Answers (2)

dhavald
dhavald

Reputation: 554

I agree with chandresh_cool. you should use 'true' option to decode the json encoded string as array, otherwise it will return an object.

moreover, file_get_contents() expects a filename (with full or relative path). When you try to give a json_encoded string, it thinks that its the file name and it will try to open it as a file, which, obviously does not exist, and thus throws an error. Try to give an existing filename and see that solves the problem.

P.s. I know this should be a comment, but due to insufficient points, I cannot comment

Upvotes: 1

chandresh_cool
chandresh_cool

Reputation: 11830

You need to set second parameter of json_encode as true to return array

$Json_Decoded = json_decode($Json_Encoded, true);

Upvotes: 0

Related Questions