php - retrning an associative array from mysqli statement result
692
I have the following code.
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;
}
The output only contents one row, the last row. how can retrieve all records?
$questions = $db->fetch_questions();
var_dump($questions);
Output of var_dump:
array
'question_title' => string 'aaaaaa' (length=6)
'question' => string 'aaaaaaaaaaaaaaaaaaaa' (length=20)
Answer
Solution:
You need to append onto
$arr
via[]
, not assign its value directly. Otherwise you are overwriting it on each loop iteration.