namespace Login
{
public partial class logForm : Form
{
public logForm()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection(@"Data Source=.;Initial Catalog=testData;Integrated Security=True;Encrypt=True;TrustServerCertificate=True");
private void logUser_Click(object sender, EventArgs e)
{
String username, user_password;
username = txt_user.Text;
user_password = txt_pass.Text;
try
{
String query = "SELECT * FROM loginTable WHERE email or username = '"+txt_user.Text+"' AND password = '"+txt_pass.Text+"'";
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dtable = new DataTable();
sda.Fill(dtable);
if (dtable.Rows.Count > 0) //reads dataTable
{
username = txt_user.Text;
user_password = txt_pass.Text;
Form1 f1 = new Form1(); //opens window after successful login
f1.Show();
this.Hide();
}
else
{
MessageBox.Show("Incorrect login Information, please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt_user.Clear(); //clears inputs after failure
txt_pass.Clear();
txt_user.Focus();
}
}
catch
{
MessageBox.Show("Error");
}
finally
{
con.Close();
}
}
}
}
In the string query line, it works when I just have username = txt_user or email = text_user, but it doesn’t work when I try to integrate both to make exceptions for either. My main focus is to be able to use both email or username in the login field. I’ve tried reordering the way I’ve written the OR statement as well so I don’t know what the answer is.
>Solution :
con.Open();
String query = "SELECT * FROM loginTable WHERE (email = @usernameOrEmail OR username = @usernameOrEmail) AND password = @password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@usernameOrEmail", txt_user.Text);
cmd.Parameters.AddWithValue("@password", txt_pass.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dtable = new DataTable();
sda.Fill(dtable);
Parameterized query to prevent SQL injection hence the update you see in the query. And I added those parameters to assigned variables (which you declared). OR has lower precedence than AND, which fails the intended query that you were trying to structure ->
(email = 'inputValue') OR (username = 'inputValue' AND password = 'inputPassword')
To correctly check if either email or username matches, and if the password matches, you need to group the OR conditions together with parentheses:
SELECT * FROM loginTable WHERE (email = 'inputValue' OR username = 'inputValue') AND password = 'inputPassword'
Let me know in the comments if I am correct.