So I have an index.php page that spits out data from two tables on my database. The first table, questions
contains one column for my QuestionID and looks like this:
qid
----
1
2
3
The second table called answers
contains two columns, one for my AnswersID and the other which links to my QuestionsID on the questions
table, and it looks like this:
aid | aqid
----|-----
1 | 3
2 | 1
3 | 1
So on my index.php page, I basically want to echo out every qid
row from the questions
table and beside it the total number of answers (aid
rows from the answers
table) corresponding to each QuestionID.
To put simply, the result I want achieved on my index.php page is this:
QuestionID: 1 / Answers: 2
QuestionID: 2 / Answers: 0
QuestionID: 3 / Answers: 1
But based on my current code I am having trouble achieving this result. It keeps echoing out the wrong number of rows for each table. This is the unwanted result I am getting:
QuestionID: 1 / Answers: 3
QuestionID: 2 / Answers: 3
QuestionID: 3 / Answers: 3
So how would I fix this to achieve the correct result? This is my current code:
<?php
$sql = "
SELECT questions.*, GROUP_CONCAT(answers.aqid) AS aqid
FROM questions
LEFT JOIN answers
ON questions.qid=answers.aqid
GROUP BY questions.qid
";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$qid = $row["qid"];
$aqid = $row["aqid"];
$row_cnt = $result->num_rows;
?>
<div>
QuestionID: <?php echo $qid; ?>
<?php foreach($answers as $answer): ?>
Answers: <?php echo $row_cnt; ?>
<?php endforeach; ?>
</div>
<?php } ?>
Thank you for your help.