Friday, January 28, 2011

Login - check database if user exists... (c#)

I have managed to do the following...

string connectionString = "datasource=localhost;username=xxx;password=xxx;database=xxx";
MySqlConnection mySqlConnection = new MySqlConnection(connectionString);

string selectString =
"SELECT username, password " +
"FROM forum_members " +
"WHERE username = '" + frmUsername.Text + "' AND password = '" + frmPassword.Text + "'";

MySqlCommand mySqlCommand = new MySqlCommand(selectString, mySqlConnection);
mySqlConnection.Open();
String strResult = String.Empty;
strResult = (String)mySqlCommand.ExecuteScalar();
mySqlConnection.Close();

if (strResult.Length == 0)
{
Label1.Text = "INCORRECT USER/PASS!"
//could redirect to register page
} else {
Label1.Text = "YOU ARE LOGGED IN!";
//set loggin in sessions variables
}

5 comments:

jigisha prajapati said...

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
string select = "SELECT p_name,p_password FROM tbl_profile WHERE p_name = '"+txt12.Text+"' AND p_password = '"+txt13 .Text +"'";
SqlCommand cmd1 = new SqlCommand (select,con );
con.Open();
string check = String .Empty ;
check = (String)cmd1.ExecuteScalar();

if (check.Length > 0)
{
lbl3.Text = "YOU ARE LOGGED IN!";
Response.Redirect("home.aspx");
}

else
{
lbl3.Text = "INCORRECT USER/PASS!";
Response.Redirect("registration.aspx");
}
con.Close();

jigisha prajapati said...

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
string select = "SELECT p_name,p_password FROM tbl_profile WHERE p_name = '"+txt12.Text+"' AND p_password = '"+txt13 .Text +"'";
SqlCommand cmd1 = new SqlCommand (select,con );
con.Open();
string check = String .Empty ;
check = (String)cmd1.ExecuteScalar();

if (check.Length > 0)
{
lbl3.Text = "YOU ARE LOGGED IN!";
Response.Redirect("home.aspx");
}

else
{
lbl3.Text = "INCORRECT USER/PASS!";
Response.Redirect("registration.aspx");
}
con.Close();
i have error:Object reference not set to an instance of an object.

bala said...

Bala : i too have the same error ... did anyone have solution for it...

Anonymous said...

YOur database may not contain any data . so fill it first .

mj said...

Please close the connection At the End Friends