How To Count Rows With Zend_Db_Table

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:

  1. SELECT count(*) FROM myTableName WHERE someColumn=’someValue’;
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:

  1. $sql = $this->select()
  2. ->from($this, ‘COUNT(*)’)
  3. ->where(‘parent_id=?’, $this->id);
  4. echo $this->fetchRow($sql)->num;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s