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)
629

Answer

Solution:

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

Source

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.