views:

512

answers:

1

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();
+4  A: 

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