-2

In C# desktop application I use MySqlConnection MySqlCommand cmd.CommandText:

"select * from reg where username='" + user + "' and password='" + pass + "' and key='" + key + "'";

to selects records, but I'm trying to figure out, how to use OR operator with condition, if I want check both user OR email from single input like string UserOrEmail = textBox1.Text.Trim();.

Looks like condition works for username= or email=, but in this case following values checking does not works, seems like I have to use some correct way here:

"select * from reg where username='" + UserOrEmail + "' or email='" + UserOrEmail + "' and password='" + pass + "' and key='" + key + "'";
  • 3
    first of all: ***use parameterised queries*** - otherwise you're wide open for SQL injection attacks and prone to numerous syntax errors in the future. second: ***never ever ever ever*** store passwords as plain text - ***hash them***. (and no: "i'm still learning" is not a valid excuse - learn it _the right way_ from the start) – Franz Gleichmann Jan 01 '21 at 14:57
  • [Operator Precedence](https://dev.mysql.com/doc/refman/8.0/en/operator-precedence.html) – Luuk Jan 01 '21 at 14:58

1 Answers1

2

You need parentheses because the operator AND has higher precedence than OR:

"select * from reg where (username='" + UserOrEmail + "' or email='" + UserOrEmail + "') and password='" + pass + "' and key='" + key + "'";

Or use the operator IN:

"select * from reg where '" + UserOrEmail + "' in (username, email) and password='" + pass + "' and key='" + key + "'";
forpas
  • 160,666
  • 10
  • 38
  • 76