Reputation: 37136
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
Upvotes: 2
Views: 472
Reputation: 11217
See my answer in other thread: Zend_Db: How to get the number of rows from a table?
Upvotes: 1
Reputation: 1221
Counting your comments in the database is more efficient, because
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.
Upvotes: 7
Reputation: 1078
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.
Upvotes: 3