I am having trouble figuring out how to work an if statement into my PHP containing a MySQL Query. Here's what I have so far (it's unfinished):
$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);
Basically, what I'm trying to say is that if any of the variables are set to 'any' then I want those variables to represent all the possibilities (there's like five possibilites in the form for each variable). I figured I'd use arrays in the where clause (like WHERE industry IN ($industry)) but then it wouldn't work if someone actually did pick a variable.
I may be a little off track but am having trouble wrapping my mind around it. Any help would be greatly appreciated. Thanks!
If I did not misunderstand your question, I would do this.
$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);
You can remove single quote around the variables in the query if you are sure they are integer.
Build your where clause gradually
$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);