6

I'm just wondering what the syntax is to do a db select in Zend Framework where two values are true. Example: I want to find if a user is already a member of a group:

$userId = 1;
$groupId = 2;
$db = Zend_Db_Table::getDefaultAdapter();
$select = new Zend_Db_Select($db);
$select->from('group_members')
    ->where('user_id = ?', $userId); //Right here. What do I do about group_id?
$result = $select->query();
$resultSet = $result->fetchAll();
Andrew
  • 227,796
  • 193
  • 515
  • 708

2 Answers2

16

You can use multiple where clauses which will be ANDed together by default:

$select->from('group_members')
    ->where('user_id = ?', $userId)
    ->where('group_id = ?', $groupId);
Adam Franco
  • 81,148
  • 4
  • 36
  • 39
  • I'm getting an exception when trying to do the first example: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s) – Andrew Dec 04 '09 at 02:51
  • Strange, I've used both techniques in the past against MySQL using the PDO adapter. I guess I'll need to set up a table to test. It may be that your database type or adapter doesn't support the syntax I suggested. – Adam Franco Dec 04 '09 at 03:07
  • What database/adapter combination are you using? – Adam Franco Dec 04 '09 at 03:09
  • I was able to get the second one working. There's nothing wrong with your code in the second one. I realized my problem was that I was handling the result wrong. – Andrew Dec 04 '09 at 03:18
  • I've now tested the first version and found it was resulting in the following SQL: SELECT `group_members`.* FROM `group_members` WHERE (user_id = 1, 1 AND group_id = 1, 1) BTW: You can use `print $select->__toString();` to output example SQL from the statement. Anyway, it seems that passing and array of parameters actually doesn't work with Zend_Db_Select (I must have been confusing this with using PDO directly), so I've removed that invalid part of the answer. – Adam Franco Dec 04 '09 at 03:38
5

Just In case someone wants to add an OR condition to a select with multiple params

$select = $db->select()
         ->from('products',
                array('product_id', 'product_name', 'price'))
         ->where('price < ?', $minimumPrice)
         ->orWhere('price > ?', $maximumPrice);

For more view the Zend Select manual Docs: zend.db.select

Mohit Padalia
  • 1,549
  • 13
  • 10