0

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
)

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.