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->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.