1

I want to login to the program using c#, with my username and password that's stored to the SQL Database in phpmyadmin. This is what I have so far.

private void button1_Click(object sender, EventArgs e)
        {
            MySqlConnection connection;
            string server = "localhost";
            string database = "login";
            string uid = "root";
            string password = "";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";


            connection = new MySqlConnection(connectionString);

            try
            {
                connection.Open();
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    Form1 frm = new Form1(this);
                    frm.Show();
                    Hide();
                }
                else
                {
                    MessageBox.Show("Database Connection Failed", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An Error Occured, Try again later.", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
            }
        }

It connects to the database, however I don't want it to show the form1 Until both a valid Username and Password have been entered. I'm guessing I need to use SELECT * FROM but I'm not exactly sure how to go about it.

1
  • The connection would fail if the credentials are incorrect and an exception would be thrown and thus catch (Exception ex) block would execute. Commented Aug 13, 2016 at 14:06

3 Answers 3

5

You can use this way to see if username and password match

MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = @username and password=@password";
command.Parameters.Add("@username", txtUserName.Text);
command.Parameters.Add("@password", txtPassword.Text);
var count = cmd.ExecuteScalar();

if(count>0)
    //Logged In

Just to say, if you use a query like

cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = '"+txtusernam +"'";

You will be open to SQL Injection

Warning

As Steve mentioned in comments Passwords in clear text are a vulnerability of the same magnitude of string concatenation

Sign up to request clarification or add additional context in comments.

4 Comments

Just add a warning here. Passwords in clear text are a vulnerability of the same magnitude of string concatenation.
@Steve Thanks. I will add it to my answer
Thank you, and Passwords are hashed.
command.Parameters.Add has a red line under command. Same for db.conn.CreateCommand, db.conn isn't recognized. What should I be 'using'
1

you make try this one

using(var con = new MysqlConnection{ ConnectionString = "your connection string " })
{
    using(var command = new MysqlCommand{ Connection = con })
    {
       con.Open();

       command.CommandText = @"SELECT level FROM userTable WHERE username=@username, password=@password";
       command.AddWithValue("@username", txtusername.Text);
       command.AddWithValue("@password", txtpassword.Text);

       var strLevel = myCommand.ExecuteScalar();

       if(strLevel == DBNULL.Value || strLevel == Null)
       {
          MessageBox.Show("Invalid username or password");
          return;
       }
       else
       {
          MessageBox.Show("Successfully login");
          hide(); // hide this form and show another form
       }

}

}

Comments

-2

use below Query

Select * from UsersTable Where Username='"+username+"' AND password='"+password+"' 

Then you can make a if condition that if your query contain a result (rows) then users authenticated (exists in Table)

Note:Select query may fetch multiple users having same userName and password, its upto you to keep usersname unique in table

5 Comments

DO NOT TEACH STRING CONCATENATION, please.
Nothing against you of course. This problem is so diffuse that I feel really bad when I see an answer that use this approach. I can't remove the downvote now, but you can always delete the answer or fix the problem (but at this point your answer will be the same as the other one). Sorry.
No, I will not delete,It will play warning mark for others so that they avoid this approach,Thanks again
Uhm, not sure if the community has the same stand about this. We will see.
@Steve, every gentlemen will dislike spoon feeding,

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.