0

Is it possible to dynamically create a select statement with multiple where() clauses? Suppose a function that takes multiple arguments. If the Nth argument is non-empty, add a ->where('sth = ?", $value) clause in the statement and do that for all arguments.

Now, the trivial way would be with a huge switch case but it feels wrong. If the where() clause accepted arrays, it would be very easy but what about now?

Thanks!

hakre
  • 193,403
  • 52
  • 435
  • 836
johnjohn
  • 4,221
  • 7
  • 36
  • 46
  • Have you tried if that works? I mean it probably just works. And what do the docs tell about this? You have not linked any docs. Hmm. And your question can benefit from some formattings of the source-code that makes it easier to read. My 2 cents. – hakre Jun 20 '12 at 20:25
  • 1
    Should these clauses be added as `AND` or `OR` conditions? What about taking an arrays as binded arguments? – raina77ow Jun 20 '12 at 20:29
  • @hakre: There 's no need for "docs", if you are familiar with zend_db, it 's obvious what I 'm saying. Also, there 's no thing to try to see if "it just works", it 's an open question. – johnjohn Jun 22 '12 at 00:29

2 Answers2

0

I've pointed in comment that it's not a trivial task to implement a universal WHERE wrapper: that's why (I think) ZF developers decided to go with a more-o-less simple method, which takes basically takes an SQL expression - and not an array.

It'd more-o-less easy to implement such function for your case:

function whereX(Zend_Db_Select $select, array $args) {
  foreach($args as $argExpression => $argValue) {
    $select->where($argExpression, $argValue);
  }
}

... then use it by something like this...

whereX($select, array('price < ?' => $minimumPrice, 'price > ?' => $maximumPrice));

But that function should be tweaked when you decide to use 'OR' conditions - or to make some more complex clauses. As it becomes more and more complex, its simplicity deteriorates...

I suppose that's why it's not included to Zend standard package - at least, at present.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

In case anyone is looking for an alternative (Zend Framework 1.12.3) :

 $where = array();
 foreach($delete_ids as $delete_cond)
          $where[]=$db_adapter->quoteInto ('id=?', $delete_cond);

  $where = implode(' OR ', $where);
  $where = '('.$where.') AND '.$db_adapter->quoteInto('somethingEse=?', $something);

This will give you the result of:

WHERE (as many OR conditions as you like of the **same** column) AND (single condition that must
also be met)

You could tweak it up a bit with raina77ow's answer in order to have different column conditions inside the ORs conditions.

Chayemor
  • 3,577
  • 4
  • 31
  • 54