从mysqli语句结果返回一个关联数组

时间:2013-01-16 17:20:45

标签: 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)

1 个答案:

答案 0 :(得分:3)

您需要通过$arr附加到[],而不是直接分配其值。否则,您将在每次循环迭代时覆盖它。

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