4

Possible Duplicate:
Grouping WHERE clauses with Zend_Db_Table_Abstract

I need to create something like this:

select name from table where active = 1 AND (name LIKE 'bla' OR description LIKE 'bla')

The first part is easy:

$sqlcmd = $db->select()
->from("table", "name")
->where("active = ?", 1)

Now comes the tricky part. How can I nest? I know that I can just write

->orWhere("name LIKE ? OR description LIKE ?", "bla")

But thats wron, because I need to dynamically change all the parts. The query will be built all the time the script runs. Some parts get deleted, some altered. In this example I need to add those OR-s because sometimes I need to search wider. "My Zend Logic" tells me that the correct way is like this:

$sqlcmd = $db->select()
->from("table", "name")
->where("active = ?", 1)
->where(array(
    $db->select->where("name LIKE ?", "bla"),
    $db->select->orWhere("description LIKE ?", "bla")
))

But that doesn't work (atleast I dont remember it working).

Please. Can someone help me to find a object oriented way for nesting "where"-s

Community
  • 1
  • 1
Reyo
  • 148
  • 3
  • 11
  • I had the same issue. See the answer to my question here: http://stackoverflow.com/questions/1179279/grouping-where-clauses-with-zend-db-table-abstract – Mark May 10 '10 at 18:20

2 Answers2

1

Here's an example from the ZF manual

  // Build this query:
  //   SELECT product_id, product_name, price
  //   FROM "products"
  //   WHERE (price < 100.00 OR price > 500.00)
  //     AND (product_name = 'Apple')

  $minimumPrice = 100;
  $maximumPrice = 500;
  $prod = 'Apple';

  $select = $db->select()
               ->from('products',
                      array('product_id', 'product_name', 'price'))
               ->where("price < $minimumPrice OR price > $maximumPrice")
               ->where('product_name = ?', $prod);

It should fit your needs

mike
  • 5,047
  • 2
  • 26
  • 32
  • 5
    This example doesn't prevent SQL Injection like the `?` replacement does. I don't know why it's even in the manual. – Sonny Oct 12 '10 at 17:00
  • Well, I believe the manual tries to show that it's possible to construct the query even without the `?`. But I agree, non-experienced developers might write code which is not safe. – mike Oct 13 '10 at 12:08
-3

To build this query:

SELECT product_id, product_name, price FROM "products" WHERE (price > 100.00) AND (price < 500.00)

use this code:

$minimumPrice = 100;
$maximumPrice = 500;

$select = $db->select()
             ->from('products',
                    array('product_id', 'product_name', 'price'))
             ->where('price > ?', $minimumPrice)
             ->where('price < ?', $maximumPrice);
Jon Adams
  • 24,464
  • 18
  • 82
  • 120
  • 2
    This is an incorrect answer since it doesn't show how to combine some expressions by OR surrounded by parenthesis. – Jon Adams Aug 04 '11 at 20:29