Retrieving the Highest Value in a Database Field using Zend_Db_Select

Written by James Mansson on March 16, 2013 Categories: Databases, Zend Framework 1

Sometimes you need to know the highest value in a particular database field. For instance, when inserting a new row into a table, you may need the value of a particular field to be one greater than the previous highest value in order to place the record next in sequence.

Assuming that we have a Zend_Db_Table object $dbTable and that the field in questions is called sequence, we could use the following code to generate the next value:

$select = $dbTable->select();
$select->from($this, array('MAX(`sequence`) as s'));
$rows = $dbTable->fetchAll($select);
$sequence = $rows[0]->s + 1;

We start by retrieving a Zend_Db_Select object, which can be used to construct the query. The call to the MySQL MAX function is specified as the field we wish to retrieve, with s being used as the alias to the field. When we retrieve the value, we add one to it. This value can then be used when inserting the new row.

No Comments on Retrieving the Highest Value in a Database Field using Zend_Db_Select

Leave a Reply

Your email address will not be published. Required fields are marked *