To display comments recursively I'm using this:
function fetch_article_comments($article_id, $parent_id) {
$app = new Connection();
if ($parent_id <= 0) {
$parent_id = NULL;
}
$sql = "SELECT * FROM recursive WHERE article_id = :article_id AND comment_parent <=> :parent_id ORDER BY comment_timestamp ASC";
$query = $app->getConnection()->prepare($sql);
$query->execute(array(':article_id' => $article_id,
':parent_id' => $parent_id));
return $query->fetchAll();
}
And to display the comments:
function display_comments ($article_id, $parent_id=0, $level=0) {
$comments = fetch_article_comments($article_id, $parent_id);
foreach($comments as $comment) {
$comment_id = $comment->comment_id;
$member_id = $comment->member_id;
$comment_text = $comment->comment_text;
$comment_timestamp = $comment->comment_timestamp; //get timeAgo
// RENDER
?>
<div class="comment">
<b><?= timeAgoInWords($comment_timestamp); ?></b><br>
<?= $comment_text ?><br>
<a href="#" class="replyLink" data-comment-id="<?= $comment_id ?>"><span class="uk-icon-comment-o"> reply</span></a>
<a href="recursive.php?delete=<?= $comment_id ?>"><span class="uk-icon-trash-o"> delete</span></a>
<form action="recursive.php" method="post" class="uk-form comment_form" id="<?= $comment_id ?>">
<fieldset data-uk-margin>
<input type="hidden" name="id" value="<?= $article_id ?>" />
<input type="hidden" name="parent" value="<?= $comment_id ?>" />
<input type="text" placeholder="Comment" name="svar">
<button class="uk-button">Comment</button>
</fieldset>
</form>
<?php
//Recurse
display_comments($article_id, $comment_id, $level+1);
echo '</div> <!-- /comment -->';
}
}
?>
And the comments is then echoed on the page calling the display_comments().
<div clasS="uk-width-1-1">
<?= display_comments(2); ?>
</div>
(the 2 is the post ID)
As you can see there's a lot of HTML inside the function, it's not ideal. How can the code be improved to remove the HTML and maybe foreach the results?
<?=when callingdisplay_comments()because you have no return value in that function, you directly write to output buffer with "echo" and "non php content" in your function body. \$\endgroup\$