使用foreach循环的简单查询不起作用,但没有工作

时间:2016-11-21 12:29:42

标签: php sql pdo foreach

我的查询问题毫无意义。

public function getGroup(){

    if(2 > 0){
        $query = "SELECT * FROM products ";
        $array = array(1);
        foreach($array as $n){
            $query .= " AND ID '$n'";
        }
        return $query;
    } else{
        $query = "SELECT * FROM products WHERE ID = 1 ";
        return $query;
    }
}

2 个答案:

答案 0 :(得分:2)

你的if语句中没有WHERE。因此,您的查询将如下所示:SELECT * FROM products AND ID '$n' ....请注意=之后也不会ID

    public function getGroup(){

        if(2 > 0){
            $query = "SELECT * FROM products WHERE";
            $array = array(1);
            $i=0;
            foreach($array as $n){
                if($i==0) {
                    $query .= " ID = '$n'";
                }
                else {
                    $query .= " AND ID = '$n'";
                }
                $i++;
            }
            return $query;
        } else{
            $query = "SELECT * FROM products WHERE ID = 1 ";
            return $query;
        }
    }

答案 1 :(得分:0)

我想你想要这样

public function getGroup(){
    if(2 > 0){
        $array = array(1);
        $query = "SELECT * FROM products WHERE ID in ('$array')";           
        return $query;
    } else{
        $query = "SELECT * FROM products WHERE ID = 1 ";
        return $query;
    }
}