What function is equal to mysql_num_rows in Magento?
For Magento, the proper equivalent is PHP's count()
function.
Magento usually uses Varien_Data_Collection
instances 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_Collection
class, you'll see, that this class does implement PHP's Countable interface and the proper count()
method for this interface:
class Varien_Data_Collection implements IteratorAggregate, Countable
{
:
public function count()
{
$this->load();
return count($this->_items);
}
:
}
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:
$collection = Mage::getModel('catalog/product')
->getCollection()
->addFieldToFilter(
'status',
Mage_Catalog_Model_Product_Status::STATUS_ENABLED
);
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. by
$n = count($collection);
PHP's core count()
function will detect that the passed argument $collection
implements a Countable
interface and has its own count()
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.