2016-07-17 65 views
1

我想從兩個數據庫表使用令牌從第一個表中獲取數據我試圖讓第二個表中的團隊名稱。然後將它添加到數組中以最終打印出一個json數組。低於我的代碼看看:SQL數據到使用PHP json數組給出HTTP錯誤500

$dbh = new PDO("mysql:host=localhost;dbname=dbnameabc", $username, $password); 

$sql = "SELECT * FROM chatbox order by id desc"; 

$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC); 
$return = []; 

foreach ($result as $row) { 

    $postid = $row['id']; 
    $token = $row['token']; 
    $gpslat = $row['gpslat']; 
    $gps  = $row['gps']; 
    $postmsg = $row['msg']; 

    //echo $postid + " is id " + $token + " is token " + $postmsg + " is postmsg " + $gps + " is gps and " + $gpslat; 

    $team; 

    $sqlx = "SELECT * FROM logintable WHERE token='$token'"; 
    $resultx = $dbh->query($sqlx)->fetchAll(PDO::FETCH_ASSOC); 


    foreach ($resultx as $rowx) { 
     $team = $rowx['name']; 

    } 

    $return[] = [ 
     'postmsg' => $postmsg, 
     'token' => $token, 
     'gps'  => $gps, 
     'gpslat' => $gpslat 
    ]; 

} 
$dbh = null; 

header('Content-type: application/json'); 
echo json_encode($return); 

做上述然而引發我一個錯誤HTTP錯誤500,我應該提下的是echo語句我上面的評論讓我像10.1421321一個隨機數。那麼問題是什麼?類似的代碼在我測試過的另一個表上工作正常,但不知道爲什麼這不起作用。

更新:有什麼不對的第二個查詢($resultx = $dbh->query($sqlx)->fetchAll(PDO::FETCH_ASSOC);)的連接,因爲第一個提供超過$團隊等領域工作正常,如果我不使用第二個查詢我可以打印JSON加團隊名稱,但我如何獲得第二個工作?

+2

內部服務器錯誤意味着生成錯誤日誌。您是否檢查過服務器的錯誤日誌以獲取更多信息? – dimlucas

+1

顯示錯誤:http://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display – rjdown

+0

另外,它會很高興爲我們提供什麼'var_dump($ return)'循環結束後。 –

回答

1

json_encode函數沒有錯。它工作正常。

問題是這樣的: $ resultx = $ dbh-> query($ sqlx) - > fetchAll(PDO :: FETCH_ASSOC);

您正在調用fetch all查詢的結果,失敗並返回false。嘗試在控制檯/ GUI中運行SQL查詢並查看輸出結果。

如果你想看到PDO返回的特定錯誤使用以下功能:

而且改變你的代碼到2線,檢查,如果查詢是有效的:

$stmt = $dbh->query($sqlx); 
if($stmt!=false){ 
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 
}