3

我想在我的 sql 查询的键和值对参数之间添加“AND”,但我不知道如何。我已经尝试搜索网络但无法找到解决方案。

       $cdatahome = fetchCategory(array("status"=>"1","home"=>"1")); 

       function fetchCategory(array $conditions){
        $db = Core::getInstance();

            $sql = "SELECT id, title FROM ruj_category WHERE ";

            $params = array();
            foreach ($conditions as $column => $value) {
            if (preg_match('/^[a-z-.]+$/', $column)) {

            $sql .= "$column = ?";
            $params[] = $value;

     }
    }           
            $sql .= " order by title asc";  
            $res = $db->dbh->prepare($sql);
            $res->execute(array_values($params));
                $res = $res->fetchAll(PDO::FETCH_ASSOC);        

            return $res;
4

4 回答 4

5
$where = array();
foreach ($conditions as $column => $value) {
    if (preg_match('/^[a-z-.]+$/', $column)) {
        $where[] = "$column = ?";
        $params[] = $value;
    }
}
$sql .= implode(' AND ', $where);
于 2012-12-13T19:30:26.130 回答
1

通常,当我想放置AND&(在 URL 的情况下)之类的东西时,我会创建一个数组并将它内爆到我想要的字符串中间。例如:

$items = array("a", "b", "c");

$output = implode(" AND ", $items);

输出:

"a AND b AND c"

在您的情况下,您可以执行 foreach 循环来构建字符串片段,然后在第二个答案列出的函数中使用AND作为胶水。implode()

于 2012-12-13T19:29:05.883 回答
1
$cdatahome = fetchCategory(array("status"=>"1","home"=>"1")); 

   function fetchCategory(array $conditions){
    $db = Core::getInstance();

        $sql = "SELECT id, title FROM ruj_category WHERE ";

        $params = array();
        $i = 0;
        foreach ($conditions as $column => $value) {
        if (preg_match('/^[a-z-.]+$/', $column)) {
        if($i != 0){
        $sql .= ' AND ';
        }
        $sql .= "$column = ?";
        $params[] = $value;
        $i++;
 }
}           
        $sql .= " order by title asc";  
        $res = $db->dbh->prepare($sql);
        $res->execute(array_values($params));
            $res = $res->fetchAll(PDO::FETCH_ASSOC);        

        return $res;
于 2012-12-13T19:31:16.710 回答
0

首先,您可以将条件放入一个数组中,就像对 $params 的值一样。喜欢$cond[]="$column = ?"然后$sql.=implode(' AND ',$cond);

在你的 foreach 中解决它:在循环集之前$first=false;和循环中做$sql.=($first?'':' AND ')."$column = ?"; $first=false;

于 2012-12-13T19:33:03.137 回答