How to fetch array from mysqli_fetch_assoc?
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;
}
精彩评论