有没有一种方法我不必在每种情况下都编写完整的查询?

时间:2020-02-18 13:03:00

标签: php sql

有没有一种方法我不必在每种情况下都编写完整的查询?

if($_GET['l'] == 1){
    $num = $db -> query("SELECT * FROM text WHERE type = '' AND gg = '1'") -> num_rows;
} 
elseif($_GET['l'] == 2){
    $num = $db -> query("SELECT * FROM text WHERE type = '' AND gg = '2'") -> num_rows;
} 
else {
    $num = $db -> query("SELECT * FROM text WHERE type = ''") -> num_rows;
}

1 个答案:

答案 0 :(得分:0)

很简单, 声明一个变量并在该变量中进行查询。

$query = "SELECT * FROM text WHERE type = ''";
if($_GET['l'] == 1){
    $query .= "  AND gg = '1'";
} 
elseif($_GET['l'] == 2){
    $query .= "  AND gg = '2'";
} 
else {
    $query .= " ";
}
    $num = $db -> query($query) -> num_rows;

希望这对您有所帮助。