Search code examples
c#mysqlmysqlcommand

MySQL select with OR operator


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 + "'";

Solution

  • 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 + "'";