Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Finding Rows by Primary Key

You can query the database table for rows matching specific values in the primary key, using the find() method. The first argument of this method is either a single value or an array of values to match against the primary key of the table.

Example 283. Example of finding rows by primary key values

= new Bugs();

// Find a single row
// Returns a Rowset
$rows $table->find(1234);

// Find multiple rows
// Also returns a Rowset
$rows $table->find(array(12345678));

If you specify a single value, the method returns at most one row, because a primary key cannot have duplicate values and there is at most one row in the database table matching the value you specify. If you specify multiple values in an array, the method returns at most as many rows as the number of distinct values you specify.

The find() method might return fewer rows than the number of values you specify for the primary key, if some of the values don't match any rows in the database table. The method even may return zero rows. Because the number of rows returned is variable, the find() method returns an object of type Zend_Db_Table_Rowset_Abstract.

If the primary key is a compound key, that is, it consists of multiple columns, you can specify the additional columns as additional arguments to the find() method. You must provide as many arguments as the number of columns in the table's primary key.

To find multiple rows from a table with a compound primary key, provide an array for each of the arguments. All of these arrays must have the same number of elements. The values in each array are formed into tuples in order; for example, the first element in all the array arguments define the first compound primary key value, then the second elements of all the arrays define the second compound primary key value, and so on.

Example 284. Example of finding rows by compound primary key values

The call to find() below to match multiple rows can match two rows in the database. The first row must have primary key value (1234, 'ABC'), and the second row must have primary key value (5678, 'DEF').

class BugsProducts extends Zend_Db_Table_Abstract
$_name 'bugs_products';
$_primary = array('bug_id''product_id');

$table = new BugsProducts();

// Find a single row with a compound primary key
// Returns a Rowset
$rows $table->find(1234'ABC');

// Find multiple rows with compound primary keys
// Also returns a Rowset
$rows $table->find(array(12345678), array('ABC''DEF'));

Zend Framework