views:

759

answers:

5

I want to find out how many rows are in a table. The database that I am using is a MySQL database. I already have a Db_Table class that I am using for calls like fetchAll(). But I don't need any information from the table, just the row count. How can I get a count of all the rows in the table without calling fetchAll()?

Solution:

This seems to be the only way to do it.

$result = $this->getDbTable()->fetchAll();
$count = $result->count();

echo $count; //47
+3  A: 

You could do a

SELECT COUNT(*)
FROM your_table
Peter Lang
+3  A: 
$dbo->setFetchMode( Zend_Db::FETCH_OBJ );
$sql = 'SELECT COUNT(*) AS count FROM @table';
$res = $dbo->fetchAll( $sql );
// $res[0]->count contains the number of rows
Rob
+2  A: 

Your ZF option is fetchAll() and then count($tableObject).

If you want to do this in a leaner way you can write a query like

SELECT COUNT(*) AS mycounter FROM table.

I haven't read or heard about a special Zend function to do this. And it makes sense that there should be none since that function would just be a wrapper for exactly such a select statement.

tharkun
Could you show how to execute that select statement to get the row count?
Andrew
+2  A: 

Counting rows with fetchAll considered harmful.

Here's how to do it the Zend_Db_Select way:

$habits_table = new Habits(); /* @var $habits_table Zend_Db_Table_Abstract */
$select = $habits_table->select();
$select->from($habits_table->info(Habits::NAME), 'count(*) as COUNT');
$result = $habits_table->fetchRow($select);
print_r($result['COUNT']);die;
Derek Illchuk
Why do you say "Counting rows with fetchAll is considered harmful"?
Andrew
Well, you're loading your entire table into memory...
Derek Illchuk
+2  A: 
$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
fireeyedboy