我如何选择2个或两者之间? 我正在尝试使用此脚本,但它返回错误。
if ($company == "ANY") {
$query_company = '*';
}
elseif ($company == "AMD") {
$query_company = 'AMD';
}
elseif ($company == "Intel") {
$query_company = 'Intel';
}
$card_data = mysqli_query($con,
"SELECT * FROM builds
WHERE
approved = 'yes'
AND manufacturer = $query_company
AND build_price BETWEEN $price_min
AND $price_max
");
(我通过GET从网址获取$ company) 有什么方法可以使它工作?感谢。
答案 0 :(得分:4)
这是你想要的吗?
SELECT *
FROM builds
WHERE approved = 'yes' and
(manufacturer = $query_company or $query_company = '*') and
build_price BETWEEN $price_min AND $price_max;
我只是将此作为您逻辑的示例发布(因此避免SQL注入等问题)。但是,我建议您在应用程序中进行两个不同的查询:
SELECT *
FROM builds
WHERE approved = 'yes' and
manufacturer = $query_company and
build_price BETWEEN $price_min AND $price_max;
和
SELECT *
FROM builds
WHERE approved = 'yes' and
build_price BETWEEN $price_min AND $price_max;
这种方法的优点是这些查询可以利用索引。第一个builds(manufacturer, approved, build_price)
和第二个builds(approved, build_price)
。使用or
(或like
)的单个查询也无法优化。
编辑:
让我更清楚第二种选择:
if ($company == "ANY") {
$sql = "SELECT *
FROM builds
WHERE approved = 'yes' and
build_price BETWEEN $price_min AND $price_max"
}
else {
$sql = "SELECT *
FROM builds
WHERE approved = 'yes' and
manufacturer LIKE '$query_company' and
build_price BETWEEN $price_min AND $price_max"
}
$card_data = mysqli_query($con, $sql);
这只是一个例子。您可以将$ sql预先分配给大多数查询,然后在if
语句中添加附加子句。这种方法有另一个优点。您可以在变量替换后打印$sql
以查看它的外观。
也就是说,您应该学习如何切换到参数化查询以防止SQL注入攻击。
答案 1 :(得分:1)
一种方法是使用LIKE
运算符(注意我已将*
替换为%
):
if ($company == "ANY") {
$query_company = '*';
}
elseif ($company == "AMD") {
$query_company = 'AMD';
}
elseif ($company == "Intel") {
$query_company = 'Intel';
}
$card_data = mysqli_query($con,
"SELECT * FROM builds
WHERE approved = 'yes'
manufacturer LIKE '$query_company'
and build_price BETWEEN $price_min
AND $price_max");