I have 2 tables with a one-to-many relationship.
Table 1:
_________________
| id | question |
|____|___________|
| 1 | question1 |
| 2 | question2 |
|____|___________|
Table 2:
______________________________
| id | answer | question_id |
|____|_________|_____________|
| 1 | answer1 | 1 |
| 2 | answer2 | 1 |
|____|_________|_____________|
While question_id
is the foreign key.
I'm trying to show the data like that:
question1
answer1 answer2
So question then the answers for this particular question.
Here is the code I have:
$query = "SELECT questions.*, answers.* FROM questions INNER JOIN answers ON questions.id = answers.question_id";
$run = mysqli_query($connect, $query);
while($data = mysqli_fetch_assoc($run)){
echo $data['question'] . '<br>';
echo $data['answer'] . '<br>';
}
This returns:
question1
answer1
question1
answer2
So how to show the question only once with the related answers to this particular question?
MySQL's GROUP_CONCAT
function might come in handy here:
$query = <<<QUERY
SELECT q.question, GROUP_CONCAT(a.answer ORDER BY q.id) answers
FROM questions q
INNER JOIN answers a ON q.id = a.question_id
GROUP BY q.question
QUERY;
$run = mysqli_query($connect, $query);
while ($data = mysqli_fetch_assoc($run)) {
echo htmlspecialchars($data['question'], ENT_QUOTES | ENT_HTML5), "<br>\n";
$answers = explode(',', $data['answers']);
echo '<pre>';
for ($i=0, $iMax = count($answers); $i < $iMax; $i++) {
if ($i > 0) echo "<br>\n";
echo ' ', htmlspecialchars($answers[$i], ENT_QUOTES | ENT_HTML5);
}
echo '</pre>';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.