2016-03-16 48 views
-1

我有以下代碼調用一個DB函數,它從表中檢索所有行,然後在JSON中回顯它們。PHP Sql,返回一行

$key = $db->getKeyPermissions(); 

    if ($key != false) { 
     // use is found 
     $response["error"] = FALSE; 
     $response["key"]["endpoint_name"] = $key["endpoint_name"]; 
     $response["key"]["live"] = $key["live"]; 
     $response["key"]["activity_name"] = $key["activity_name"]; 
     echo json_encode($response); 
    } else { 

這是DB函數

public function getKeyPermissions() 
    { 
     $stmt   = $this->conn->prepare("SELECT * FROM key_permissions WHERE 1"); 
     if ($stmt->execute()) { 
      $key = $stmt->get_result()->fetch_assoc(); 
      $stmt->close(); 
      return $key; 
     } else { 
      return NULL; 
     } 
    } 

這一切工作,但它僅返回第一行,然後停止罰款。閱讀你必須循環fetch_assoc(),但我無法得到這個工作。我希望將所有行都推入$key並返回,但所有嘗試都會導致數組轉換和非對象錯誤。一路上有人能幫助我嗎?

編輯:

public function getKeyPermissions() 
{ 
    $stmt   = $this->conn->prepare("SELECT * FROM key_permissions WHERE 1"); 
    if ($stmt->execute()) { 
     $key = array(); 

     while($row = $stmt->get_result()->fetch_assoc()) { //Call to a member function fetch_assoc() on a non-object 
      $key .= $row; // Array to string conversion 
     } 

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

'而($鍵= $ stmt-> get_result( ) - > fetch_assoc()){...}'? ......就在我頭頂 - 儘管沒有錯誤陷阱。 – CD001

+0

@ CD001之前嘗試過,但是我返回了一個非對象的數組轉換錯誤和fetch_assoc錯誤。我用我的新代碼編輯我的文章,並在返回錯誤的行後面添加註釋。 –

+1

'在非對象上調用成員函數fetch_assoc(),在這種情況下'get_result()'返回false。 – CD001

回答

3

要撥打get_result恰好一次fetch_assoc只要有行:

$result = $stmt->get_result(); 
$key = array(); 

while ($row = $result->fetch_assoc()) { 
    $key[] = $row; 
} 

return $key;