从mysqli语句返回关联数组


retrning an associative array from mysqli statement result

我有以下代码:

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)

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

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