Reputation: 55
I'm trying to build up a drop down filter system for a custom table. I have the following code but I can't seem to get it to work such that if one of the drops is not selected it still returns results based on the the selection of the second drop down:
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<select name="bt_nbs_intervention">
<option value=''>NbS intervention type</option>
<option value="3">Protection</option>
<option value="143">Restoration</option>
</select>
<select name="climate_change_impacts">
<option value=''>Climate change impacts</option>
<option value="15">Drought</option>
<option value="12">Flood</option>
<option value="25">Mangrove</option>
</select>
<input type='submit' value='Search'>
</form>
<?php
if ($_POST['bt_nbs_intervention'] === '') {
$_POST['bt_nbs_intervention'] = null;
}
if ($_POST['climate_change_impacts'] === '') {
$_POST['climate_change_impacts'] = null;
}
$bt_nbs_intervention = (int)$_POST['bt_nbs_intervention'];
$cc_impact = (int)$_POST['climate_change_impacts'];
$interventions = $wpdb->get_results($wpdb->prepare("
SELECT ID, intervention_post_title
FROM wp_cpt_combined
WHERE (bt_nbs_intervention IS NULL OR bt_nbs_intervention = %d) AND
(climate_change_impacts IS NULL OR climate_change_impacts = %d)",
$bt_nbs_intervention, $cc_impact));
if($interventions)
foreach ( $interventions as $intervention )
{
echo $intervention->intervention_post_title;
}
else {
echo "no results";
}
Essentially what I'm trying to do allow the user to select one or more of the select boxes to produce results. Such that if they only select Intervention type they get results or only Climate change impacts OR if they select both.
Hope that makes sense.
Thanks D
Upvotes: 0
Views: 53
Reputation: 1448
Can you check the following please:
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<select name="bt_nbs_intervention">
<option value=''>NbS intervention type</option>
<option value="3">Protection</option>
<option value="143">Restoration</option>
</select>
<select name="climate_change_impacts">
<option value=''>Climate change impacts</option>
<option value="15">Drought</option>
<option value="12">Flood</option>
<option value="25">Mangrove</option>
</select>
<input type='submit' value='Search'>
</form>
<?php
$where = [];
$placeholders = [];
if(!empty($_POST['bt_nbs_intervention'])){
$where[] = 'bt_nbs_intervention = %d';
$placeholders[] = (int)$_POST['bt_nbs_intervention'];
}
if(!empty($_POST['climate_change_impacts'])){
$where[] = 'climate_change_impacts = %d';
$placeholders[] = (int)$_POST['climate_change_impacts'];
}
$sql = "SELECT ID, intervention_post_title FROM wp_cpt_combined";
if(!empty($where)){
$sql .= ' WHERE ';
$i = 0;
foreach($where as $clause){
$sql .= $i == 0 ? $clause : ' AND ' . $clause;
$i++;
}
$sql = $wpdb->prepare($sql, $placeholders);
}
$interventions = $wpdb->get_results($sql);
Upvotes: 1