简体   繁体   English

请告诉这个MySQL查询中的错误

[英]Please tell the error in this mysql query

I wrote a mysql query but i am not getting the result as expected. 我写了一个mysql查询,但没有得到预期的结果。 This is to check that if the username and email is not as same as someone else's username or email but not his own user and email. 这是为了检查用户名和电子邮件是否不同于其他人的用户名或电子邮件,而不是他自己的用户和电子邮件。

I have tried many other queries like EXCEPT query 我尝试了其他许多查询,例如EXCEPT查询

$user_check_query = "SELECT * FROM users WHERE username='$username' 
OR email='$email' AND NOT id='$id'";
        $result = mysqli_query($db, $user_check_query);
        $user = mysqli_fetch_assoc($result);

        if ($user) { // if user exists
            if ($user['username'] === $username) {
            array_push($errors, "Username already exists");
            }

            if ($user['email'] === $email) {
            array_push($errors, "Email already exists");
            }
        }

This query is supposed to select row where username = username or password = password but id is not = id But when there is no change in username or email it returns error that username already exits and email already exists but it should not. 该查询应该选择其中用户名=用户名或密码=密码但id不是= id的行,但是,如果用户名或电子邮件没有更改,它将返回错误,表明用户名已经退出并且电子邮件已经存在,但不应存在。

Warning: You are wide open to SQL Injections and should really use parameterized prepared statements instead of manually building your queries. 警告:您对SQL注入持开放态度 ,应该真正使用参数化的预处理语句,而不要手动构建查询。 They are provided by PDO or by MySQLi . 它们由PDOMySQLi提供 Never trust any kind of input, especially that which comes from the client side. 永远不要相信任何形式的输入,尤其是来自客户端的输入。 Even when your queries are executed only by trusted users, you are still in risk of corrupting your data . 即使仅由受信任的用户执行查询, 您仍然有损坏数据的风险

To answer your question, You are mixing AND and OR in your WHERE clause. 为了回答您的问题,您在WHERE子句中混合使用AND和OR。 This jacks with the order/precedence of how the WHERE clause will be parsed. 这与WHERE子句的解析顺序/优先顺序有关。 With no parentheses, the WHERE clause will 'reset' when it sees an OR. 如果没有括号,则WHERE子句在看到OR时将被“重置”。 For example, your query will be interpreted as "where username equals username, or, while no longer considering username, email equals email AND also id is not id." 例如,您的查询将被解释为“其中用户名等于用户名,或者,当不再考虑用户名时,电子邮件等于电子邮件,并且id也不是id”。

When you put parentheses, you change how is it interpreted by grouping the username=username OR email = email together, and after that, also check the id. 加上括号后,您可以通过将username = username或email = email分组在一起来更改其解释方式,然后再检查id。

You probably want: 您可能想要:

SELECT * FROM users WHERE (username='$username' 
OR email='$email') AND NOT id='$id'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM