12

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()?

Andrew
  • 227,796
  • 193
  • 515
  • 708

7 Answers7

27
$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
Decent Dabbler
  • 22,532
  • 8
  • 74
  • 106
8

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
  • 5,638
  • 1
  • 29
  • 29
5

Proper Zend-Way is to use Zend_Db_Select like this:

$sql = $table->select()->columns(array('name', 'email', 'status'))->where('status = 1')->order('name');
$data = $table->fetchAll($sql);
$sql->reset('columns')->columns(new Zend_Db_Expr('COUNT(*)'));
$count = $table->getAdapter()->fetchOne($sql);

This is how it's done in Zend_Paginator. Other option is to add SQL_CALC_FOUND_ROWS before your column list and then get the number of found rows with this query:

$count = $this->getAdapter()->fetchOne('SELECT FOUND_ROWS()'); 
Tomáš Fejfar
  • 11,129
  • 8
  • 54
  • 82
  • it's Zend_Db_Table instance. Or it can be Zend_Db_Adapter as well. The metod is in both. It returns Zend_Db_Table_Rowset for DbTable and array for Adapter... – Tomáš Fejfar Jun 16 '11 at 05:56
  • This answer is particularly useful if you need to count the results of a contrived query that you have lost the original result set for... +1 – nzn Oct 30 '17 at 06:59
3

You could do a

SELECT COUNT(*)
FROM your_table 
Peter Lang
  • 54,264
  • 27
  • 148
  • 161
3
$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
  • 47,999
  • 5
  • 74
  • 91
2

I'm kind of a minimalist:

public function count()
{
    $rows = $db->select()->from($db, 'count(*) as amt')->query()->fetchAll();
    return($rows[0]['amt']);
}

Can be used generically on all tables.

stagl
  • 501
  • 3
  • 18
2

Add count capability to your Zend_DB Object To count all table rows

public function count()
{
    return (int) $this->_table->getAdapter()->fetchOne(
        $this->_table->select()->from($this->_table, 'COUNT(id)')
    );
}
Roy Toledo
  • 643
  • 4
  • 20