2013-01-16 38 views
2

我有以下代碼。從mysqli語句返回一個關聯數組結果

public function fetch_questions($count=null) 
{ 
    $stmt = $this->mysqli->prepare("SELECT question,question_title FROM questions order by id"); 
    $stmt->execute(); 

    $stmt->bind_result($question,$question_title); 

    $arr = array(); 
    while ($stmt->fetch()) { 
     $arr = array('question_title'=>$question_title,'question'=>$question); 
    } 
    $stmt->close(); 

    return $arr; 
} 

輸出內容只有一行,最後一行。如何檢索所有記錄?

$questions = $db->fetch_questions(); 
var_dump($questions); 

輸出的var_dump:

array 
    'question_title' => string 'aaaaaa' (length=6) 
    'question' => string 'aaaaaaaaaaaaaaaaaaaa' (length=20) 
+0

其實,我很確定它是返回*最後*行... –

+0

是的,最後一行。 – msoa

回答

3

您需要通過[]追加$arr,而不是它的價值直接分配。否則,你會在每次循環迭代中覆蓋它。

while ($stmt->fetch()) { 
    $arr[] = array('question_title'=>$question_title,'question'=>$question); 
    //-^^^^ 
}