我正在建立一个网站,用户可以选择一个出租房产,有两个字段,他们可以选择,家具和宠物。两个选择框中的选项均为“是”和“否”。
<select name="furnished">
<option value="">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<select name="pets">
<option value="">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
我正在根据用户在这些字段中选择的内容编写SQL语句。
$sql = 'SELECT *
FROM properties
WHERE num_bedrooms >= ' . $_GET['num_bedrooms'] .
' AND num_bathrooms >= ' . $_GET['num_bathrooms'];
if($_GET['furnished'] == 'yes') { //if the furnished is set to yes
$sql .= ' AND furnished = "yes" OR furnished = "partially"';
} else if($_GET['furnished'] == 'no') { //if the furnished is set to no
$sql .= ' AND furnished = "no" OR furnished = "description"';
}
if($_GET['pets'] == 'yes') { //if the pets is set to yes
$sql .= ' AND pets = "yes" OR pets = "cats" OR pets = "dogs"';
} else if($_GET['pets'] == 'no') { //if the pets is set to no
$sql .= ' AND pets = "no" OR pets = "description"';
}
如果用户选择“是”,我希望它显示所有提供的属性(是)或部分提供(部分)。如果用户选择“否”,我希望它显示所有未提供的属性(否)或具有特殊描述(描述)的属性。
如果用户对宠物选择“是”,我希望它显示允许所有宠物的所有属性(是)或仅允许猫(猫)或仅允许狗(狗)的属性。如果用户选择“否”,我希望它显示所有不允许宠物的属性(否)或具有特殊描述(描述)的属性。
例如,如果用户在“家具”上选择“是”,在“宠物”上选择“是”,则这是输出的SQL语句:
SELECT * FROM properties
WHERE num_bedrooms >= 1
AND num_bathrooms >= 1
AND furnished = "yes" OR furnished = "partially"
AND pets = "yes" OR pets = "cats" OR pets = "dogs"
问题在于它目前会在where子句中返回符合家具或宠物要求的结果,而我需要它返回符合where子句中所提供的和宠物要求的结果。
因此,它将返回一个结果,其中说明“家具”设置为“是”,并且宠物设置为“否”。 如何将所有结果返回到带有设置的设置为是和宠物设置为是?
我的SQL语句出了什么问题?
答案 0 :(得分:4)
AND
位于运算符优先级OR
之前,因此您的查询类似于
SELECT * FROM properties
WHERE
(num_bedrooms >= 1 AND num_bathrooms >= 1 AND furnished = "yes")
OR (furnished = "partially" AND pets = "yes")
OR pets = "cats"
OR pets = "dogs"
这不是你所期望的。尝试
SELECT * FROM properties
WHERE num_bedrooms >= 1
AND num_bathrooms >= 1
AND (furnished = "yes" OR furnished = "partially")
AND (pets = "yes" OR pets = "cats" OR pets = "dogs")
甚至更好
SELECT * FROM properties
WHERE num_bedrooms >= 1
AND num_bathrooms >= 1
AND furnished IN ("yes", "partially")
AND pets IN ("yes", "cats", "dogs")
您不应该SELECT *
尝试命名您需要的列!
答案 1 :(得分:3)
将parens放在各种OR
'事物上。
$sql .= ' AND (furnished = "yes" OR furnished = "partially")';
$sql .= ' AND (pets = "yes" OR pets = "cats" OR pets = "dogs")';
等等。