多个If Else语句跳过其他语句



问题是我无法到达第三个"else-if语句";场景如下:
我有3个HTML文本框->最小值、最大值和搜索关键字。如果2个文本框有值,如果我把值放在2个文本盒中,我想达到第3个,但实际情况是它只返回到第一个if语句。

<?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// ";
}
?>

else if仅在前一个if条件为false时执行。一系列if/else if将在第一个真条件下停止。因此,只有当条件相互排斥时,才应使用此选项。如果同时填写了$price_min$price_max,则第一个if将成功,因此它不会执行任何else if测试。您应该先测试是否设置了,然后再自己检查它们中的任何一个。

iif (!empty($price_min) && !empty($price_max)) {
$sql .='WHERE price BETWEEN '.$price_min.' AND '.$price_max;
} else if (!empty($price_min)) {
$sql .='WHERE price >='.$price_min;
} else if (!empty($price_max)) {
$sql .='WHERE price <='.$price_max;
}

然而,更好的方法是一次只检查一个变量,然后在最后收集所有WHERE条件。

$conditions = [];
if (!empty($price_min)) {
$conditions[] = 'price >='.$conn->real_escape_string($price_min);
}
if (!empty($price_max)) {
$conditions[] = 'price <='.$conn->real_escape_string($price_min);
}
if (!empty($keyword)) {
$conditions[] = 'tags LIKE "%'.$conn->real_escape_string($keyword).'%"';
}
if (!empty($conditions)) {
$sql .= 'WHERE ' . implode(' AND ', $conditions);
}

最新更新