Zend_Db: How to get the number of rows from a tabl

2019-04-04 13:09发布

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

7条回答
在下西门庆
2楼-- · 2019-04-04 13:52

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.

查看更多
Evening l夕情丶
3楼-- · 2019-04-04 13:57
$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
查看更多
smile是对你的礼貌
4楼-- · 2019-04-04 14:02

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;
查看更多
做个烂人
5楼-- · 2019-04-04 14:02

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()'); 
查看更多
甜甜的少女心
6楼-- · 2019-04-04 14:04
$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
查看更多
我命由我不由天
7楼-- · 2019-04-04 14:11

You could do a

SELECT COUNT(*)
FROM your_table 
查看更多
登录 后发表回答