如何从mysqli_fetch_assoc获取数组?

时间:2011-05-12 11:22:02

标签: php arrays mysqli

我的方法通过mysqli_fetch_assoc返回一个答案数组。我尝试根据索引提取答案。结果与预期不符。我会得到相同的答案(应该是三个答案)。

方法:

function getAnswers($id_question)
{
    $sql = 'SELECT * FROM answers WHERE question_id = '. $id_question;

    $this->db->query($sql);
    while ($answers = $this->db->fetchAssoc())
    {
        return $answers;
    }
}

使用:

$answers = getAnswers(1);
foreach($answers as $a)
{
    echo $a['answer'];
}
echo '<pre>';
print_r($answers);
echo '</pre>';

出:

11a1
Array
(
    [id_answer] => 1
    [question_id] => 1
    [answer] => answer 1
    [truth] => 1
)

1 个答案:

答案 0 :(得分:1)

您只返回第一组。您必须将数据打包到一个数组中,然后返回数组:

function getAnswers($id_question)
{
    $sql = 'SELECT * FROM answers WHERE question_id = '. $id_question;

    $this->db->query($sql);
    $data = array();
    while ($answers = $this->db->fetchAssoc())
    {
        $data[] = $answers;
    }

    return $data;
}