Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend_Db: How to get the number of rows from a table?

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

like image 608
Andrew Avatar asked Dec 18 '09 21:12

Andrew


7 Answers

$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
like image 81
Decent Dabbler Avatar answered Oct 03 '22 13:10

Decent Dabbler


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;
like image 45
Derek Illchuk Avatar answered Oct 03 '22 11:10

Derek Illchuk


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()'); 
like image 26
Tomáš Fejfar Avatar answered Oct 03 '22 13:10

Tomáš Fejfar


You could do a

SELECT COUNT(*)
FROM your_table 
like image 42
Peter Lang Avatar answered Oct 03 '22 13:10

Peter Lang


$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
like image 44
Rob Avatar answered Oct 03 '22 11:10

Rob


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.

like image 43
stagl Avatar answered Oct 03 '22 12:10

stagl


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)')
    );
}
like image 33
Roy Toledo Avatar answered Oct 03 '22 11:10

Roy Toledo