10

What is the easiest, simplest way to select the max of a column from a table using Zend_Db_Table? Basically, I just want to run this query in Zend:

SELECT MAX(id) AS maxID FROM myTable;
Rafael
  • 1,495
  • 1
  • 14
  • 25
Daniel Bingham
  • 12,414
  • 18
  • 67
  • 93

5 Answers5

11

You need to use Zend_Db_Expr to use mysql functions:

return $this->fetchAll(
            $this->select()
                ->from($this, array(new Zend_Db_Expr('max(id) as maxId')))
            )
    );
Richard Parnaby-King
  • 14,703
  • 11
  • 69
  • 129
4

You can run direct sql, using $db->query(); yours would simply be:

$db->query("SELECT MAX(id) AS maxID FROM myTable");

but if you want the object notation, then you'd do something like this:

$db->select()->from("myTable", array(new Zend_Db_Expr("MAX(id) AS maxID")));
Glen Solsberry
  • 11,960
  • 15
  • 69
  • 94
2

For those looking to just select the max id from their id column in Zend Framework 2 (maybe 3 as well), but getting this error...

While processing primary key data, a known key id was not found in the data array

...note that you'll need to alias MAX(id) as id.

Example inside a table extended from the TableGateway class:

$select = $this->sql->select();
$select->columns(['id' => new Expression('MAX(id)')]);
$maxId = $this->selectWith($select)->current()->id;
return (int) $maxId;
jabbascript
  • 345
  • 1
  • 6
  • 13
1

Another way is like this :

$select=new Zend_Db_Select($db);
$select->from(array($table),array('max($column)'));
$select->where('condition');
$answer=$db->fetchOne($select);

If You do it like this , you can edit it later easier!!!

M Rostami
  • 4,035
  • 1
  • 35
  • 39
0
$select = new Select();
$select->from('tablename');
$select->where(array('post_id', 1));
$select->columns(array('id' => new Expression('MAX(id)')));
$results = $this->getTableGateway()->selectWith($select);
I. S.
  • 31
  • 1