Question

I'm really sorry if this question has already been asked, or answered, but I can't quite seem to find what I need.

I have every other piece of this built, my only question is surrounding inline comments. I would like to do something similar to what Facebook does where they render x comments with a button to display all y comments.

However, the only two ways I can see of doing this are:

  1. Performing a SELECT in the loop that renders each item (I think anyone who might have an answer to this would agree with me that this is a terrible decision)
  2. Performing one large select to pull all comments where news_id is in a certain subset, and then use PHP to iterate over them, select the x most recent, and ignore the rest.

Neither one of these seems like a good solution; however, as they both involve a huge waste of resources.

Does anyone have a potential suggestion for implementing this?

Was it helpful?

Solution

SELECT * FROM comments_table WHERE article_id = {something} LIMIT {no_of_comments_per_page} SORT BY date DESC

This is a very simple yet powerful query for the comments.

Actual code

<?php
$sql = "SELECT * FROM comments_table WHERE article_id = 24 LIMIT 40 SORT BY date DESC";
$data = mysql_query($sql);
$comments = mysql_fetch_assoc($data);
foreach($comments as $comment){
  $ct++;
  echo "ID: {$ct}";
  echo "<br />";
  echo "Comment: {$comment["comment"]} by {$comment["user"]}";
  echo "Date: {$comment["date"]}";
}
?>

OTHER TIPS

I'd use a SELECT with a LIMIT added to the clause, ordering by 'id' in DESC order. Something like.. "SELECT * FROM comments LIMIT 3 DESC"

When the user clicks the "load more comments" button, perform some type of AJAX request with a query similar to.. "SELECT * FROM comments LIMIT X, 3 DESC"

I would do a JOIN, and sort the data out after. Something like:

SELECT articles.id, articles.text, articles.date, 
       comments.id, comments.text, comments.date
FROM articles LEFT JOIN comments ON (comments.article_id = articles.id)
WHERE {some criteria} ORDER BY articles.date, comments.date

The performance issue of having extra comments that would be hidden is really negligible - and you don't have the added overhead of making an ajax request to load the other comments when they click that 'see all' button - you can just hide them, and then display them instantly.

If you wanted only the top 40 posts, you would have to add this condition to the where clause (in fact, you could wrap whatever filtering you're doing in as well):

WHERE articles.id IN (SELECT id FROM articles ORDER by articles.date LIMIT 40)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top