0

Pro devs, I have a problem with my code in c#.net and I knew you can help me. the problem is in the Login code, every time I entered a value that is existed in the database it says "Username or password is incorrect" and when I entered a value that does not exist in the DB it says again "Username or password is incorrect" please help me thank you.

I have tried to edit the query and remove the open close in the asterisk but the output is the same.

public void checkLoginAccount()
    {
        frmMain frmLogin = new frmMain();
        con = new MySqlConnection();
        con.ConnectionString = "server=localhost;userid=root;password=alpine;port=3305;database=pos_db;pooling=false;SslMode=none";

        con.Open();
        string qry = "SELECT COUNT(*) FROM pos_db.tbllogin WHERE BINARY Username=@user AND BINARY Password=@pass";
        MySqlCommand cmd = new MySqlCommand(qry, con);
        cmd.Parameters.AddWithValue("@user", frmLogin.txtUsername.Text);
        cmd.Parameters.AddWithValue("@pass", frmLogin.txtPassword.Text);

        int count = Convert.ToInt32(cmd.ExecuteScalar());

        if (count != 0)
        {   
            MessageBox.Show("Welcome");
        }
        else
        {
            MessageBox.Show("Either username or password is incorrect!");
            return;
        }
        con.Close();
        con.Dispose();
    }

2 Answers2

4

You are creating a new form instance in your function:

 frmMain frmLogin = new frmMain();

So the username and password are always empty here:

cmd.Parameters.AddWithValue("@user", frmLogin.txtUsername.Text);
cmd.Parameters.AddWithValue("@pass", frmLogin.txtPassword.Text);

You need to use the right instance of your form.

Elias N
  • 1,430
  • 11
  • 19
-1

Try reading the rows and count in the code. That should look something like this:

string qry = "SELECT Username FROM pos_db.tbllogin WHERE BINARY Username=@user AND BINARY Password=@pass";
        MySqlCommand cmd = new MySqlCommand(qry, con);
        cmd.Parameters.AddWithValue("@user", frmLogin.txtUsername.Text);
        cmd.Parameters.AddWithValue("@pass", frmLogin.txtPassword.Text);

        mySqlDataReader reader = cmd.ExecuteReader();
        if(reader.Read() == true)
        {
            MessageBox.Show("Welcome");
        }
        else
        {
            MessageBox.Show("Either username or password is incorrect!");
            return;
        }
umair qayyum
  • 286
  • 3
  • 11