0

我试图找出执行这些类型查询的最佳方法

我想要做的是构建一个过滤器类型函数,其中我在一个数组中并构造了查询!

问题出在 PDO 之前,您可以绑定一个值,您需要准备语句,但是如果我准备语句,我无法更改查询。

让我给你看一个例子:

public function GetFeedsByFilter($filter = array())
{
    //Base Query
    $Query = 'SELECT feeds,sites,users,categories WHERE feed_site_id = site_id AND feed_uid = user_id AND feed_category_id = category_id';

    if(isset($filter['limit'])){$filter['limit'] = 30;} //Setters

    //Check the different filters
    if(isset($filter['category']))
    {
         //Here I want to bind the category
         //i can do the following
         $Query .= ' AND category_id = :cid';

         //But now I cant bind the value with $statement->bindValue
    }
}

现在我可以首先为查询构造字符串,然后执行所有 if 语句来绑定它们,但这就是太多了!

有什么想法可以克服这个问题吗?

4

1 回答 1

1

您可以使用 if 部分中的占位符填充数组。

例如

if(isset($filter['category'])){
     $query .= ' AND category_id = :cid';
     $binds['cid'] = 123; 
}

然后“准备”您的查询并在执行命令中提供绑定值作为选项

$pdo->execute($binds);

有关更多信息,请参见http://uk.php.net/manual/de/pdostatement.execute.php

于 2010-08-25T21:17:49.293 回答