Zend Framework: How to do a DB select with multiple params?
Asked Answered
E

2

7

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();
Euthenics answered 4/12, 2009 at 2:37 Comment(0)
P
17

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);
Palmary answered 4/12, 2009 at 2:41 Comment(5)
I'm getting an exception when trying to do the first example: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)Euthenics
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.Palmary
What database/adapter combination are you using?Palmary
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.Euthenics
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.Palmary
S
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

Sills answered 11/1, 2013 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.