I'm trying to loop through my MySQL database and retrieve five responses for each comment. The output should be as following
- First comment
- First response
- Second response
- ...
- Fifth Response
- Second comment
- First response
- Second response
- ...
- Fifth response
- ...
in order to achieve the above, I'm using the following SQL statement and PHP snippet
$query = $db->prepare("
SELECT c.id, c.user_update, r.id reply_id, r.response,
FROM comments AS c
LEFT JOIN (SELECT * FROM responses LIMIT 5) AS r ON (r.reply_id = c.id)
");
try {
$query->execute();
$comments = array();
$comments_replies = array();
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$comm_id = $row['id'];
$comments[$comm_id] = $row;
$comments_replies[$comm_id][] = $row;
}
foreach ($comments as $comm_id => $row) {
echo "<b>".$row['comment']."</b></br></br>";
foreach ($comments_replies[$comm_id] as $reply_id => $row) {
echo $row['response']."</br></br>";
}
}
} catch (PDOException $e) {
echo $e->getMessage();
exit();
}
but it doesn't work so I'm trying to find out what should I change to make it work - to retrieve five responses for each comment and output them as shown above.