2

On Zend_Db_Table_Abstract I'm using this code to get the count of results for my select:

$this->setTableName('visitors');
$select = $this->select()
               ->from('visitors')
               ->columns(array('total' => new Zend_Db_Expr('COUNT(*)')))
               ->where('...');
$visits = $this->_fetch($select);

Is there a better way, ie, just to return the count. This returns some other data in an array... I just want the count of results. In straight mySQl the equivalent would be select count(mycol) from visitors where ....

Owen
  • 7,347
  • 12
  • 54
  • 73

4 Answers4

4

This is untested, but should get you started:

$results = $this->getAdapter()
  ->query("SELECT COUNT(*) AS total FROM visitors WHERE ...")
  ->fetchAll();
$visits = $results[0]["total"];

You aren't required to use the Table/Select interface for every query.


update: +1 to the comment from @SMka, for pointing out that this can be even simpler:

$visits = $this->getAdapter()
  ->fetchOne("SELECT COUNT(*) AS total FROM visitors WHERE ...");
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • Your last sentence is a relief! – Owen Sep 12 '11 at 16:50
  • 1
    I worked on Zend_Db_Select, and I tried to make it clear in the docs that the interface is to help when you need to build up a query piece by piece from application logic or variables. It's not necessary to use that interface when you you can simply spell out the full SQL query in a string. *SQL is already a domain-specific language.* – Bill Karwin Sep 12 '11 at 17:01
  • @Bill Karwin but parsing SQL takes time wouldn't Zend_Db_Select with PDO extension gona save recourse ?? – Mr Coder Sep 12 '11 at 17:31
  • @jason bourne: Zend_Db_Select simply helps to put together a SQL query string. The query string is still sent to the RDBMS server, where it is parsed just like if you wrote it yourself. There is no savings. – Bill Karwin Sep 12 '11 at 17:35
4
$count = $this->select()->from($this,'COUNT(*)')->query()->fetchColumn();
Mr Coder
  • 8,169
  • 5
  • 45
  • 74
1

http://framework.zend.com/manual/en/zend.db.adapter.html

see fetchOne

$this->setTableName('visitors');
$select = $this->select()
               ->from('visitors')
               ->columns(array('total' => new Zend_Db_Expr('COUNT(*)')))
               ->where('...');
$count = $this->getAdapter()->fetchOne($select);
SMka
  • 3,021
  • 18
  • 14
0

here ya go

public function fetchCount($data)
{
    $sql = "SELECT COUNT(*) AS count FROM table WHERE field = ".$data;

    $count = $this->db->fetchOne($sql, array('count'));

    return $count;
}
Patrioticcow
  • 26,422
  • 75
  • 217
  • 337