php - retrning an associative array from mysqli statement result


I have the following code.

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


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

    return $arr;

The output only contents one row, the last row. how can retrieve all records?

$questions = $db->fetch_questions();

Output of var_dump:

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



You need to append onto$arr via[], not assign its value directly. Otherwise you are overwriting it on each loop iteration.

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

People are also looking for solutions to the problem: Php variables not adding together


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.