我无法弄清楚如何在包含MySQL查询的PHP中使用if语句。这是我到目前为止所做的事情(尚未完成):
$industry = $_GET['industry'];
$location = $_GET['location'];
$position = $_GET['position'];
$region = $_GET['region'];
if($industry=="any"){
}
if($location=="any"){
}
if($position=="any"){
}
if($region=="any"){
}
$sql_cat = "
SELECT *
FROM jobs
WHERE industry_cat='$industry' && location_cat='$location' && position_cat='$position' && region_cat='$region'
ORDER BY id DESC
";
$result_cat = $mysqli->query($sql_cat);
$num_rows_cat = mysqli_num_rows($result_cat);
基本上,我想说的是,如果任何变量设置为'any',那么我希望这些变量代表所有可能性(每个变量的形式中有五个可能性)。我想我会在where子句中使用数组(比如WHERE industry IN($ industry))但是如果有人确实选择了一个变量,它将无法工作。
我可能有点偏离轨道,但我很难绕过它。任何帮助将不胜感激。谢谢!
答案 0 :(得分:4)
如果我没有误解你的问题,我会这样做。
$sql = "SELECT * FROM jobs WHERE 1";
if($industry !== "any"){
$sql .= " AND industry_cat = '$industry'"
}
if($location !== "any"){
$sql .= " AND location_cat = '$location'"
}
if($position !== "any"){
$sql .= " AND position_cat = '$position'"
}
if($region !== "any"){
$sql .= " AND region_cat = '$region'"
}
$sql .= " ORDER BY id DESC"
$result = $mysqli->query($sql);
如果您确定它们是整数,则可以删除查询中变量的单引号。
答案 1 :(得分:0)
逐步构建where子句
$industry = $_GET['industry'];
$location = $_GET['location'];
$position = $_GET['position'];
$region = $_GET['region'];
if($industry!="any"){
$where[] = 'industry_cat=?';
$where_args[] = $industry;
}
if($location!="any"){
$where[] = 'location_cat=?';
$where_args[] = $location;
}
if($position!="any"){
$where[] = 'position_cat=?';
$where_args[] = $position;
}
if($region!="any"){
$where[] = 'region_cat=?';
$where_args[] = $region;
}
$where_clause = implode(' and ', $where);
$sql_cat = "
SELECT *
FROM jobs
where $whereclause
ORDER BY id DESC
";
$stmt = $mysqli->prepare($sql_cat);