phpzend-frameworkzend-dbzend-db-select

Zend_db_Select multiple where but with variable clauses possible?


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!


Solution

  • 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.