2013-05-08 86 views
2

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

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

你得到的错误是什么? – 2013-05-08 16:04:42

+0

你不应该将json文本插入到数据库中,除非你打算永远不要使用sql访问json文本中的任何单独的子数据。 json的传输格式,而不是存储格式。 – 2013-05-08 16:05:29

+0

@ Marc B嗯,我需要爆炸字符串来获取元素并将它们添加到数据库中。我认为这是什么JSON解码功能呢? – user2363025 2013-05-08 16:24:25

回答

0

您需要设置json_encode为真正的第二个参数返回数组

$Json_Decoded = json_decode($Json_Encoded, true); 
+0

谢谢,我试过了。但是,我仍然收到“Warning:file_get_contents({”Coords“:[{”Accuracy:“:”56“,”Latitude“:”78“,”Longitude“:”89“,”Timestamp“ :“909”}]}):无法打开流:没有这样的文件或目录在48行/home/roseanne/public_html/display_Coords.php“ – user2363025 2013-05-08 16:07:51

+0

这是其他错误,这是由于一些文件不存在。 – 2013-05-08 16:09:55

+0

@ chandresh_cool这是我得到的唯一错误。第48行是这一行:$ Json_Data = file_get_contents($ Json_Encoded); – user2363025 2013-05-08 16:12:23

1

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

此外,file_get_contents()需要文件名(具有完整或相对路径)。当你尝试给出一个json_encoded字符串时,它认为它的文件名称,它会尝试打开它作为一个文件,显然它不存在,从而引发错误。尝试给一个现有的文件名,看看解决了这个问题。

P.s.我知道这应该是一个评论,但由于分数不足,我不能评论

+0

@ dhavald我编辑了代码以包含true选项并删除了文件获取内容功能。但是,我仍然收到错误:警告:mysql_num_rows()期望参数1是资源,在/home/roseanne/public_html/display_Coords.php在线26 – user2363025 2013-05-08 19:38:15

+0

布尔给它是否成功更新数据库? – dhavald 2013-05-08 19:53:54

+0

没有,因为查询涉及使用解码数组中的变量,但我有一些涉及该解码的错误。 – user2363025 2013-05-08 19:58:44