【问题标题】:Multiple/nested "select where" with Zend_Db_Select [duplicate]Zend_Db_Select 的多个/嵌套“选择位置”[重复]
【发布时间】:2010-05-08 19:32:34
【问题描述】:

可能重复:
Grouping WHERE clauses with Zend_Db_Table_Abstract

我需要创建这样的东西:

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

第一部分很简单:

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

现在是棘手的部分。我怎样才能筑巢?我知道我只会写

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

但那是错误的,因为我需要动态更改所有部分。查询将在脚本运行时构建。有些部分被删除,有些被改变。在此示例中,我需要添加那些 OR-s,因为有时我需要进行更广泛的搜索。 “我的 Zend Logic” 告诉我正确的方法是这样的:

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

但这不起作用(至少我不记得它起作用了)。

。有人可以帮我找到一种面向对象的嵌套方式 "where"-s

【问题讨论】:

标签: zend-framework mysql zend-db zend-db-select


【解决方案1】:

这是 ZF 手册中的一个示例

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

它应该适合您的需求

【讨论】:

  • 这个例子并没有像 ? 替换那样阻止 SQL 注入。我不知道为什么它甚至在手册中。
  • 好吧,我相信手册试图表明即使没有? 也可以构造查询。但我同意,没有经验的开发人员可能会编写不安全的代码。
【解决方案2】:

构建这个查询:

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

使用此代码:

$minimumPrice = 100;
$maximumPrice = 500;

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

【讨论】:

  • 这是一个错误的答案,因为它没有显示如何用括号括起来的 OR 组合一些表达式。
猜你喜欢
  • 2013-07-28
  • 2022-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 2013-08-04
  • 1970-01-01
相关资源
最近更新 更多