2

我无法弄清楚如何在包含 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);

基本上,我想说的是,如果任何变量设置为“任何”,那么我希望这些变量代表所有可能性(每个变量的表格中有五个可能性)。我想我会在 where 子句中使用数组(比如 WHERE Industry IN ($industry)),但是如果有人真的选择了一个变量,它就行不通了。

我可能有点偏离轨道,但我很难把它包起来。任何帮助将不胜感激。谢谢!

4

2 回答 2

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);

如果您确定它们是整数,则可以删除查询中变量周围的单引号。

于 2012-12-18T05:52:18.803 回答
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);
于 2012-12-18T05:54:04.903 回答