views:

442

answers:

2

Hello,

I created a query for the zend framework, in which I try to retrieve the sum of a column, in this case the column named 'time'. This is the query I use:

$this->timequery = $this->db_tasks->fetchAll($this->db_tasks->select()->from('tasks', 'SUM(time)')->where('projectnumber =' . $this->value_project));


$this->view->sumtime = $this->timequery;

Echoing the query tells me this is right. But I can't echo the result properly. Currently I'm using:

echo $this->sumtime['SUM(time)'];

Returning the following error:

Catchable fatal error: Object of class Zend_Db_Table_Row could not be converted to string in C:\xampp\htdocs\BManagement\application\views\scripts\tasks\index.phtml  on line 46

Line 46 being the line with the echo in my view.

I've been searching now for two days on how to figure this out, or achieve the same result in a different way. Tried to serialize the value, but that didn't work either.

Is there somebody who knows how to achieve the total sum of a database column?

Any help is greatly appriciated!

note: Pretty new to zend framework...

A: 

The SQL you want is probably:

SELECT SUM(time) AS time_sum FROM tasks ...

Not sure how to do this in Zend. Then:

echo $this->sumtime['time_sum'];
dave1010
Already tried that as well, but I still get the same error back. I'm guessing the query is good but I'm not echoing the result back in a proper way...
Rick de Graaf
+2  A: 

Hi Rick,

Zend_Db has some nice utility methods like fetchAll (which you're using) to fetch different types of data:

  • fetchAll - for a set of rows
  • fetchRow - for a single row
  • fetchOne - for a single cell

Most simply:

$sum = $db->fetchOne('SELECT SUM(time) FROM tasks WHERE project_number = ?', $this->value_project);

You can use Zend_Db_Select with these methods too, like in your question:

//note that the SUM(time) part is passed as a Zend_Db expression, as it is not a column
$select = $this->db_tasks->select()
                         ->from('tasks', new Zend_Db_Expr('SUM(time)'))
                         ->where('projectnumber =' . $this->value_project);

$this->timequery = $this->db_tasks->fetchOne($select);

This works because the Zend_Db_Select object implements a toString method, to produce SQL.

David Caunt
Hi David,First of all thanks! But I'm still getting an error bacK:Fatal error: Call to undefined method Application_Model_DbTable_Tasks::fetchOne()Does this means it cannot find fetchOne in the class?Changing it to fetchRow or fetchAll again gives the error that it cannot convert to a string.Almost there!
Rick de Graaf
If figured it out:The last sentence had to be: $this->view->timequery = $this->db_tasks->getAdapter()->fetchOne($select);Thanks a lot!
Rick de Graaf
Ah - I had assumed that $this->db_tasks was a database adapter, not a Zend_Db_Table. You have the right solution with getAdapter
David Caunt