I am trying to create a homepage where I will output question with its answers
I have a question which has 3 answers, but when I create the object it only return 1 answer, whereas I need it to return the array of answers. Do I need to create additional class answers in order to do that?
My code:
include("connect-database.inc.php");
$question_query = "SELECT
questions.questionID,
answers.answer,
questions.question,
questions.feedback,
questions.mark,
questions.questionTypeID
FROM questions
JOIN answers ON questions.questionID=answers.questionID";
$questionList=array();
$answerList = array();
try {
$mysqliResult = $link->query($question_query);
while($var=$mysqliResult->fetch_assoc()){
$questionList[$var['questionID']]=new questions($var['question'],$var['feedback'], $var['mark'], $var['questionTypeID'], $var['answer']);
}
} catch (Exception $e) {
echo "MySQLi Error Code: " . $e->getCode() . "<br />";
echo "Exception Msg: " . $e->getMessage();
exit();
}
var_dump($questionList);
class questions {
public function __construct($question, $feedback, $mark, $questionTypeID, $answerList){
$this->question = $question;
$this->feedback = $feedback;
$this->mark = $mark;
$this->questionTypeID = $questionTypeID;
$this->answers($answerList);
}
public function answers($answers) {
$answers = array();
$this->answers = $answers;
}
}
I have tried to change to query and retrieve data by answerID, but then I get the same question 3 times. Can anybody help with the solution?
$answers = array();insideanswers()method? You overrides the given parameter, to store an empty array.$questionList[$var['questionID']] = new, you override previous results with the key$var['questionID'].$questionList[$var['questionID']][] = new questions