php - Multiple If-Else statement skipping the other statements
The problem is that I can't reach the 3rd "else if statement" where the scenario is like this:
I have 3 textboxes in HTML -> minimum value, maximum value and search keyword. if the 2 textbox has values I want to reach the 3rd if I put values in 2 textboxes, but what's happening is it's only returning to the 1st if statement.
<?php
$price_min = $_POST['price_min'];
$price_max = $_POST['price_max'];
$keyword = $_POST['keyword'];
$sql = 'SELECT * FROM products ';
if (!empty($price_min)) {
$sql .='WHERE price >='.$price_min;
} else if (!empty($price_max)) {
$sql .='WHERE price <='.$price_max;
} else if (!empty($price_min) && !empty($price_max)) {
$sql .='WHERE price BETWEEN '.$price_min.' AND '.$price_max;
} else if (!empty($keyword) && !empty($price_min)) {
$sql .='WHERE (tags LIKE "%'.$keyword.'%") AND (price >='.$price_min.')';
} else if (!empty($keyword) && !empty($price_max)) {
$sql .='WHERE (tags LIKE "%'.$keyword.'%") AND (price <='.$price_max.')';
} else if (!empty($keyword) && (!empty($price_min) AND !empty($price_max)) {
$sql .='WHERE (tags LIKE "%'.$keyword.'%") AND (price BETWEEN '.$price_min.' AND '.$price_max.')';
} else {
echo "all are empty// ";
}
?>
Answer
Solution:
else if
is only executed if the previousif
condition was false. A series ofif/else if
will stop at the first true condition. So this should only be used when the conditions are mutually exclusive. If both$price_min
and$price_max
are filled in, the firstif
will succeed, so it won't perform any of theelse if
tests. You should test for both being set before checking for either of them by themselves.However, a much better way to do this is to just check for one variable at a time, and then collect all the
WHERE
conditions at the end.