简体   繁体   English

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

[英]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. 我需要将php编码数组的元素插入数据库,而我完全被卡住了。 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. 我首先使用json编码通过SQL查询(我成功完成)从数据库中获取数据,但是现在我需要做相反的事情。 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());

I agree with chandresh_cool. 我同意chandresh_cool。 you should use 'true' option to decode the json encoded string as array, otherwise it will return an object. 您应该使用'true'选项将json编码的字符串解码为数组,否则它将返回一个对象。

moreover, file_get_contents() expects a filename (with full or relative path). 此外, file_get_contents()需要一个文件名(具有完整或相对路径)。 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. 当您尝试提供json_encoded字符串时,它认为它是文件名,它将尝试将其作为文件打开,该文件显然不存在,并因此引发错误。 Try to give an existing filename and see that solves the problem. 尝试提供一个现有的文件名,看看能解决问题。

Ps I know this should be a comment, but due to insufficient points, I cannot comment 附言:我知道这应该是一则评论,但由于要点不足,我无法发表评论

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

$Json_Decoded = json_decode($Json_Encoded, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM