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();

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

I'm getting an exception when trying to do the first example: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)
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.
What database/adapter combination are you using?
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.
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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.