2014-12-04 70 views
0

我使用php連接到mysql數據庫,並使用以下函數從數據庫中檢索多行,然後將它們添加到數組並將它們發回。我收到內部服務器錯誤或500x錯誤消息。我不確定這段代碼有什麼問題。我試圖找出它,但無法得到它。用新的mysqli查詢獲取多行?

public function getUnreadMessages($uname){ 
      $stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?"); 
      $status = 'unread'; 
     $stmt->bind_param("ss", $uname, $status); 
     if ($stmt->execute()) { 
       $stmt->bind_result($col1, $col2, $col3); 
       $stmt->store_result(); 
       $resp = array(); 
      while($stmt->fetch()){ 
         $row = array(); 
         array_push($row, $col1, $col2, $col3); 
         array_push($resp, $row);    
      } 
      $msg = array('msgid' => $msgid,'title' => $title,'fromuname' => $fromuname); 
      $stmt->close(); 
      return $msg; 

     } else { 
         $stmt->close(); 
        return NULL; 
     } 
    } 

我應該怎麼做呢?是處理返回的結果函數如下

$app->get('/inbox', 'authenticate', function() use ($app){ 
     ob_start("ob_gzhandler"); 
     global $global_user_name; 
     $db = new DbHandler(); 
     $resp = $db->getUnreadMessages($global_user_name); 
     $msgs = array(); 
     $msgs['status'] = 'success'; 
     $msgs['version'] = 0.1; 
     array_push($msgs, $resp); 

     $app->response()->header('Content-Type', 'application/json'); 
     echo json_encode($msgs); 
     exit; 

}); 
+0

那是後話與服務器端沒有工作的代碼,它甚至還沒有達到最終的代碼....看看您是否使用實際的URL或不? – 2014-12-04 06:54:59

+0

我正在使用Chrome開發人員工具來監視請求和響應標頭。該請求正在被服務器發送和接收。服務器用500條消息關閉連接。如果網站存在錯誤,我會多次遇到此問題。至於錯誤記錄,我確實啓用了調試。有時會出現一些解析錯誤或微不足道的錯誤。其他時間他們不 – 2014-12-04 15:52:32

+0

服務器是否支持通過URL登錄?我的意思是通過網址傳遞的憑據? – 2014-12-04 17:50:54

回答

0

的PDO方法自動化,這是$ stmt->使用fetchall():d

public function getUnreadMessages($uname) 
{ 
    $stmt = $this->conn->prepare("SELECT msgid,title,fromuname FROM messages WHERE touname = ? and status = ?"); 
    $stmt->execute([$uname, 'unread'])) 
    return $stmt->fetchAll(PDO::FETCH_ASSOC); 
} 

返回false如果沒有被發現或者類似的東西:

$msg = [ 
    [ 
     'msgid' => 2746, 
     'title' => 'Random title', 
     'fromuname' => 'SomeGuy' 
    ], 
    [ 
     'msgid' => 754, 
     'title' => 'Some title', 
     'fromuname' => 'Random Name' 
    ], 
    [ 
     'msgid' => 27686, 
     'title' => 'Unreadable title', 
     'fromuname' => 'Training dummies' 
    ], 
]; 
+0

之外我仍然收到錯誤。我已經發布了適用於該功能的代碼 – 2014-12-04 15:48:33

0

我解決了我的問題。這是我在一個循環內創建一個數組。這似乎是不允許的。下面是最終

public function getUnreadMessages($uname){ 

      $stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?"); 
       $status = 'unread'; 
       $stmt->bind_param("ss", $uname, $status); 
      $result = $stmt->execute(); 
      $stmt->bind_result($col1, $col2, $col3); 
      $stmt->store_result(); 
      $outer = array(); 
      $inner = array(); 
      while($stmt->fetch()){ 
        array_push($inner, $col1, $col2, $col3); 
      } 
      array_push($outer, $inner); 
      return $outer; 
      $stmt->close(); 
    }