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?
2
Answers
You can separate new Question instance creating from add new answers to existing Question like:
PHPize – online PHP environment
Just use separate queries for both question and answer.
If you want to use
group by answerID
, of course it will return result with multiple answer with same question. Mysql return result as flat. Just save the value inside an array as suchThen you build the class object by looping through each
questionID
.