0

I can't find my problem. Can anyone help me to check it. I'm new in C#.

  public void Btnchange_Click(object sender, EventArgs args)

 MySqlConnection con = new MySqlConnection("server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234");
        MySqlDataAdapter sda = new MySqlDataAdapter("select Password from user.register where Password='" + textoldpassword.Text + "'", con);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        if (dt.Rows.Count.ToString() == "1")
        {
            if (textnewpassword.Text == textconfirmpassword.Text)
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand("update user.register set Password ='" + textconfirmpassword.Text + "' where Password ='" + textoldpassword.Text + "'", con);
                cmd.ExecuteNonQuery();

                con.Close();
                lblmsg.Text = "Succesfully Updated";
                lblmsg.ForeColor = Color.Green;
            }

            else
            {
                lblmsg.Text = "New password and confirm password should be same!";
            }

I expect it can update and change my password.

Lau Weiqi
  • 45
  • 1
  • 7
  • 1
    What do you mean by 'nothing happen'. Is there a response at all? Does the data update? Storing plain text passwords is asking for trouble. Writing SQL vulnerable code is asking for trouble (especially with plain text passwords). – danblack Feb 18 '19 at 07:54
  • sorry Sir, i'm new .The data didn't update – Lau Weiqi Feb 18 '19 at 07:56
  • 2
    @LauWeiqi Do you get an exception? If so, on what line? Have you debugged your code? If so, does it enter and successfully run the innermost if-block? You need to be more precise about what is not working. – kaffekopp Feb 18 '19 at 07:59
  • yes sir i have debug it and run .It can run successfully without error but the data wont update when i press change button – Lau Weiqi Feb 18 '19 at 08:01
  • 3
    C# isn't a language I'm strong in however I see no code associated with buttons. Please read comments carefully. If you set a breakpoint at the inner `if` statement, does it stop there when run? [See this](https://stackoverflow.com/questions/7174792/does-using-parameterized-sqlcommand-make-my-program-immune-to-sql-injection) for sql injection prevention. [See this](https://stackoverflow.com/questions/2138429/hash-and-salt-passwords-in-c-sharp) for handing passwords more securely. – danblack Feb 18 '19 at 08:11
  • 3
    Also you're updating _all_ users that happen to have the same password. You should also check for a matching `userid` in your `WHERE` clause. – Markus Deibel Feb 18 '19 at 08:15
  • 4
    @LauWeiqi google for `Bobby Tables` to understand what is wrong with this code. Best case, someone enters `';--` to delete all passwords. Worst case, someone writes `'; drop table user.register;--`. Don't use dynamic SQL, use parameterized queries. *Don't* write your own user management code either. The proper way to store passwords is to salt them, hash them at least 1000 times with a strong cryptographic algorithm and only store the hash. Frameworks like ASP.NET Core Identity already do this correctly – Panagiotis Kanavos Feb 18 '19 at 08:34
  • 1
    @LauWeiqi finally, you're using MySQL classes with a SQL Server connection string. This code will never work, it will throw when you call `sda.Fill()` or `con.Open()` – Panagiotis Kanavos Feb 18 '19 at 08:36
  • 1
    @LauWeiqi just in case you think the password problem is an exaggeration, this is such an old and well known issue there are *many* scripts that try multiple dangerous password variations and URLs to try that could end up injecting malign SQL into a form. Just google for `SQL Injection Google Dorks`. – Panagiotis Kanavos Feb 18 '19 at 08:39
  • Thanks a lot guys , i will work on it. – Lau Weiqi Feb 18 '19 at 09:02

1 Answers1

3

There are many many (mostly) minor mistakes in your code:

  • use some kind of Id fields in your sql tables
  • never do an update like you did (update the field WHERE this field is equals to...)
  • create your own class and bind the query result to this class
  • when a class implements IDisposable interface, always use the keyword 'using'
  • never ever user string concatenation in sql queries!!! SQL INJECTION!!! always use parametrized sql queries

Here's a simple example for your form. Let's suppose your user.register table has the following columns: - Id - Username - Password

Now let's create your own class (maybe right under your button click event, so it can be private this time):

private class MyUser
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

Then your button click event should look like this:

private void Btnchange_Click(object sender, EventArgs e) {
if (!textnewpassword.Text.Trim().Equals(textconfirmpassword.Text.Trim()))
{
    throw new ArgumentException("New password and confirm password should be same!");
}

List<MyUser> myUsers = new List<MyUser>();

using (MySqlConnection con =
    new MySqlConnection(
        "server=localhost;user id=root;persistsecurityinfo=True;database=user;password=1234"))
{
    using (MySqlCommand cmd = new MySqlCommand("select * from user.register where Username=@user and Password=@pass", con))
    {
        cmd.Parameters.AddWithValue("@user", textusername.Text.Trim());
        cmd.Parameters.AddWithValue("@pass", textoldpassword.Text.Trim());

        if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();

        using (MySqlDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                myUsers.Add(new MyUser
                {
                    Id = (int)dr["Id"],
                    Username = dr["Username"].ToString(),
                    Password = dr["Password"].ToString()
                });
            }
        }

        if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
    }

    if (!myUsers.Any())
    {
        throw new ArgumentException("No users found with the given username/password pair!");
    }

    if (myUsers.Count != 1)
    {
        throw new ArgumentException("More than 1 user has the same username and password in the database!");
    }

    MyUser user = myUsers.First();
    user.Password = textnewpassword.Text.Trim();

    using (MySqlCommand cmd = new MySqlCommand("update user.register set Password=@pass where Id=@id"))
    {
        cmd.Parameters.AddWithValue("@pass", user.Password);
        cmd.Parameters.AddWithValue("@id", user.Id);

        if (cmd.Connection.State != ConnectionState.Open) cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        if (cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close();
    }
} }

...and so on.

Attila
  • 64
  • 2