How To Count Rows With Zend_Db_Table
Posted on November 18th, 2009 in Web Development, Zend Framework | No Comments »
This is just a quick tip but seems to stump a lot of people, probably because it is not at all clear in the Zend Reference how to do this. So if you want to count the number of rows in a table using SQL you would write something like:
SELECT count(*) FROM myTableName WHERE someColumn='someValue';
But when you are using a Zend_Db_Table it’s a little confusing how to get the “count(*)” part to work because Zend_Db_Table likes to throw errors saying that it can’t be joined with other tables. So, in your Zend_Db_Table class, here is the syntax you can use:
$sql = $this->select()
->from($this, 'COUNT(*)')
->where('parent_id=?', $this->id);
echo $this->fetchRow($sql)->num;