Question

I have a section in my site where I do need to count the number of comments for a specific post.I actually already built a function for retrieving all the data in the comments DB table (function getComments).

the comments DB table structure is : id(PK) | authorId | datetime | postId | text

Now, since I just need to count them (the comments),I was wondering if,in term of server resources/redundancy is better to use :

$comments=new Comment();
$comments->getComments();
echo count($comments);

Or I'm better build another function (apart from 'getComments')like :

function countComments($postid)
{
  //count comments per post
}

thanks

Luca

Was it helpful?

Solution

Counting your comments in the database is more efficient, because

  1. Only the count is transferred, so you save bandwidth between your database and the php process.
  2. You save IO because the result isn't generated and the data isn't read from disk
  3. A RDBMS is optimized for such functions.

Assuming, that you use Zend_Db something like this should work:

$query = $db->select()->from('comments', 'count(*)');
$count = $db->fetchOne($query);

Code redundancy isn't a problem IMHO here, it's just one or two lines.

OTHER TIPS

I always would prefer to use a separate function which uses MySQL to count the posts. Because if you just need the count you would not have to request the whole rowset, which increases performance and saves resources.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top