What function is equal to mysql_num_rows in Magento?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For Magento, the proper equivalent is PHP’s
count()function.Why?
Magento usually uses
Varien_Data_Collectioninstances to fetch result sets containing multiple records. Varien implements the Lazy Load Pattern for these collections, that is, no result set will be fetched before you really need it.If you take a look at the
Varien_Data_Collectionclass, you’ll see, that this class does implement PHP’s Countable interface and the propercount()method for this interface:If you’re asking yourself now, what got lazy loading to do with counting records, then you need to know that querying a collection the usual Magento way, e.g. like this:
does not fetch the result set at all. But, how do you count records of a result set which hasn’t been fetched yet? Right, you can’t. And neither can
mysql_num_rows. It fetches the result set first.Now, when you call
count()on the collection, e.g. byPHP’s core
count()function will detect that the passed argument$collectionimplements aCountableinterface and has its owncount()method defined, so it will call that one.This leads to really fetching the result set* and storing it to
$this->_items, which finally allows counting the records and return the number.* In Magento you can also call
foreach ($collection as $product)to really fetch the result set, but that’s another story.