用或运算符选择语句

时间:2012-01-27 19:37:24

标签: php mysql

如果我有数据库行settings [id,user,pass,sos]

,请说

我有以下mysql语句

$username$password可以是任何

$query = mysql_query ("SELECT * FROM `settings` WHERE user='$username' AND pass='$password'")

我想说

SELECT * FROM `settings` WHERE user='$username' AND pass='$password' or sos=$username and sos=$password

所以我的问题是如何在select语句中使用or

像我想说的那样

user='$username'
pass='$password'
or
sos = both $username and $password

感谢您的帮助

6 个答案:

答案 0 :(得分:3)

您需要使用一些括号来确保您在相关的用户名/密码对上正确匹配:

SELECT * 
FROM `settings` 
WHERE (user='$username' AND pass='$password') 
    or (sos='$username' and sos='$password')

但是,您确实需要使用参数化查询,因为上述内容受SQL注入攻击。有关如何执行此操作的示例,请参阅此处:

How can I prevent SQL injection in PHP?

答案 1 :(得分:1)

你可以做到

SELECT * 
FROM `settings` 
WHERE (user='$username' AND pass='$password') or (sos='$username' and sos='$password')

答案 2 :(得分:1)

你只需要一些括号内的小组。我在第二组中添加了单引号,您最初错过了它们。

SELECT * 
FROM `settings`
WHERE 
  (user='$username' AND pass='$password')
  OR (sos='$username' AND sos='$password')

答案 3 :(得分:1)

使用括号:

SELECT * 
FROM `settings` 
WHERE 
   (user='$username' AND pass='$password')
   OR
   (sos='$username' AND sos='$password')

答案 4 :(得分:1)

我认为你需要括号

SELECT * FROM `settings` WHERE (user='$username' AND pass='$password') or (sos=$username and sos=$password)

答案 5 :(得分:1)

它不能完全像那样吗?我会写

WHERE (user = '$username' AND pass = '$password')
OR ('$username' = '$password' AND sos = '$username');