I’m trying to create a price filter using a html form and php prepared statements. My form looks like this:
<form class="hotel-form" action="#" method="get">
<label for="price-per-night" class="land-label">Price-per-night:</label>
<select class="filter-form" name="price" id="price-per-night">
<option value="100">£0-100</option>
<option value="101-200">£101-200</option>
<option value="300">£201-300</option>
</select>
<input type="submit" value="Filter" class="filter">
</form>
and my prepared statement looks like this:
if ($price = $_REQUEST['price']) {
$asql = "SELECT * FROM accommodation WHERE price_per_night < ? ORDER BY price_per_night";
$stmt = mysqli_prepare($conn, $asql);
mysqli_stmt_bind_param($stmt, "i", $price);
mysqli_stmt_execute($stmt);
$queryresults3 = mysqli_stmt_get_result($stmt);
}
elseif ($price = $_REQUEST['price']) {
$asql = "SELECT * FROM accommodation WHERE price_per_night > ? ORDER BY price_per_night";
$stmt = mysqli_prepare($conn, $asql);
mysqli_stmt_bind_param($stmt, "i", $price);
mysqli_stmt_execute($stmt);
$queryresults4 = mysqli_stmt_get_result($stmt);
}
the if statement successfully displays all accommodation with a price less than $100, however the elseif statement does not work. It displays all accommodation. Is there a way to display accommodation correctly based on the values in the html form?
2
Answers
You need to uniform your HTML values. So;
0-100
,101-200
,201-300
etc. and then which ever value is selected and submitted in the HTML form, then you run some string functions (such asexplode
) to split on the-
character and take the left side value as the minimum and the right side value as the maximum and plug them both into your SQL accordingly.Your else/if also looks like code repetition which is indicative of bad design.
EXAMPLE:
HTML
PHP
You have used the assignment operator for comparison, change the = to == like this