Performing SELECT WHERE IN using Zend_Db_Select

Written by James Mansson on January 2, 2013 Categories: Databases, Zend Framework 1

Constructing a normal SELECT statement using Zend_Db_Select is straightforward enough. Take the following code snippet as an example of how it works:

$select = $dbTable->select();
$select->where('status = ?', $status);
$rows = $dbTable->fetchAll($select);

Assuming the table name is order and the value of $status is ordered this will execute the SQL query:

SELECT * FROM order WHERE status = 'ordered'

I recently needed to perform a SELECT by a range of values, rather than a single value as in the above. The SQL query I needed to execute was something like:

SELECT * FROM machine WHERE owner_id IN (1,2,3)

In this case, the parameters of IN would vary according to circumstances. It turned out there was a simple way to do this using Zend_Db_Select:

$select = $dbTable->select();
$select->where('owner_id IN(?)', $ownerIds);
$rows = $dbTable->fetchAll($select);

Here $owners was an array of the owner IDs. The function where automatically expands this into a comma-separated list. It also escapes any list entries as appropriate.

No Comments on Performing SELECT WHERE IN using Zend_Db_Select

Leave a Reply

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