开发者

How to fetch array from mysqli_fetch_assoc?

开发者 https://www.devze.com 2023-03-05 21:53 出处:网络
My method returns an array of answers by mysqli_fetch_assoc. I try to extract the answer according to the index. The result does not match expectations. I would get the same answers(should be three an

My method returns an array of answers by mysqli_fetch_assoc. I try to extract the answer according to the index. The result does not match expectations. I would get the same answers(should be three answers).

method:

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

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

use:

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

out:

开发者_如何转开发
11a1
Array
(
    [id_answer] => 1
    [question_id] => 1
    [answer] => answer 1
    [truth] => 1
)


You are returning only the first set. You will have to pack the data into an array and then return the array:

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消