-1

So I know this is a often asked question but I want to check if the username is already taken in the database using c#. I tried this:

MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM tablename WHERE(name = '" + tb1.Text + "');");

cmd2.Connection = connect;
connect.Open();

string unt = "";
try
{
    MySqlDataReader dr;
    dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        unt= dr.GetString("name");
    }
    dr.Close();
}
catch (Exception ex)
{
    errorbox.Content = ex.Message;
}
finally
{

    connect.Close();

}
if(unt == "" || unt == "0") {
    continuel = false;
    tb2.Text = "User " +tb1.Text+ " doesn't exist!";
    Popup1.IsOpen = true;

}

Its a WPF project and the variable 'continuel' is set to true by default. The code doesn't recognize if a user doesn't exist.

Soumendra Mishra
  • 3,483
  • 1
  • 12
  • 38
Loli
  • 1
  • 3

1 Answers1

0

First off your code is vulnerable to sql inject, you should never concatenate values into a query. secondly you can do a count and execute a scalar. Not I stripped down your code a little you'll have to add error handling back.

bool userExists = false;
private String sql = "SELECT COUNT(*) FROM tableName WHERE name = @usernameparam;";
MySqlCommand m = new MySqlCommand(sql);
m.Parameters.AddWithValue("@usernameparam", tb1.Text.Trim());
int userCount = Convert.ToInt32(m.ExecuteScalar());

if(userCount>0) 
{
    userExists = true;
}

//use userExists variable to evaluate if user exists
Jpsh
  • 1,697
  • 12
  • 17
  • Probably it is better to use https://stackoverflow.com/questions/5528854/usage-of-mysqls-if-exists – Steve Sep 12 '20 at 16:10
  • Thank you for your answers! I am new to this and really appreciate the help – Loli Sep 13 '20 at 15:03