将php json编码数组插入数据库

时间:2013-05-08 16:00:00

标签: php sql json decode encode

我需要将php编码数组的元素插入到数据库中,我完全被卡住了。我首先使用json编码来使用SQL查询从数据库中获取数据(我已成功完成),但我现在需要能够做相反的事情。如果有人可以提供帮助,我会非常感激。这是我工作的第二天,我做得不好。以下是我的代码:

    $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());

2 个答案:

答案 0 :(得分:1)

我同意chandresh_cool。你应该使用' true'用于将json编码的字符串解码为数组的选项,否则它将返回一个对象。

此外,file_get_contents()需要一个文件名(包含完整路径或相对路径)。当你尝试给出一个json_encoded字符串时,它会认为它是文件名,并且它会尝试将其作为文件打开,这显然不存在,因此会抛出错误。尝试提供现有的文件名,看看能解决问题。

P.S。我知道这应该是一个评论,但由于分数不足,我无法发表评论

答案 1 :(得分:0)

您需要将json_encode的第二个参数设置为true以返回数组

$Json_Decoded = json_decode($Json_Encoded, true);