我制作了一个普通表格,您可以输入用户名并选择性别。
现在到PHP进行数据库搜索。
$full_name = mysql_real_escape_string($_POST["search"]);
$sex = mysql_real_escape_string($_POST["sex"]);
list($firstname, $lastname) = array_map('ucfirst', explode(' ', $full_name));
$query = "SELECT firstname, lastname, id, user_name, sex, last_access, bostadsort FROM users WHERE firstname LIKE '$firstname' OR lastname LIKE '$lastname' AND sex = '$sex'";
$result1 = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result1);
echo $count;
如果我进入Jenni Jackson(存在)并选择“男性”,我仍然可以获得1美元的数量,但Jenni Jackson是一名女性,并且在性别专栏中有女性...我试过回声$性别看如果它真的是你在表单中选择的那个,那么$ sex的价值就是正确的。
答案 0 :(得分:3)
您需要在查询中使用括号:
WHERE (firstname LIKE '$firstname' OR lastname LIKE '$lastname') AND sex='$sex'";
没有括号,您的查询等同于:
WHERE firstname LIKE '$firstname' OR (lastname LIKE '$lastname' AND sex='$sex')";
并且由于firstname
条件匹配,将返回该行。
这是因为AND
precedence
超过OR
答案 1 :(得分:1)
尝试添加一些括号
$query = "
SELECT
firstname,
lastname,
id,
user_name,
sex,
last_access,
bostadsort
FROM users
WHERE
(
firstname LIKE '$firstname'
OR lastname LIKE '$lastname'
)
AND sex = '$sex'";
答案 2 :(得分:0)
您需要在WHERE
子句中使用括号,以便数据库知道哪个优先(AND或OR):
WHERE (firstname LIKE '$firstname' OR lastname LIKE '$lastname') AND sex = '$sex'
答案 3 :(得分:0)
您在同一个WHERE子句中组合AND和OR条件
你的意思是
(firstname LIKE '$firstname' OR lastname LIKE '$lastname') AND sex = '$sex'
或
firstname LIKE '$firstname' OR (lastname LIKE '$lastname' AND sex = '$sex')