Friday, March 9, 2012

Problem matching input username with database

I tried matching the input username with the database. Althoughthe input value is the same as the database, but it doesnt goes intothe if statement to increase the "stat" value. Please advise what wentwrong. Thanks.
protected void btnEnter_Click(object sender, EventArgs e)
{
if (txtUsername.Text.Length > 0)
{
status++;
Label3.Text = "";
}
else
{
Label3.Text = "Please enter a username";
}
if (txtPassword.Text.Length > 0)
{
status++;
Label4.Text = "";
}
else
{
Label4.Text = "Please enter a password";
}

if (status == 2)
{
int stat = 0;
string mySelectQuery = "SELECT * FROM users";
SqlConnection myConnection = new SqlConnection("DataSource=WINSON-COMP;Initial Catalog=winson;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
try
{
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
stat = 0;
string user = (string)myReader["username"];
string pass = (string)myReader["password"];
if (user == txtUsername.Text){
stat++;
}else {
Label3.Text = "Incorrect Username";
}
if (pass == txtPassword.Text){
stat++;
}else{
Label4.Text = "Incorrect Password";
}
if (stat == 2)
{
Server.Transfer("shopping.aspx");
}
}
myReader.Close();
}
finally
{
myConnection.Close();
}
}
}for what you are doing, why would you want to do that way? To check if the user exists you dont need to get back all the rows in the table and match them on the server. You should be *sending* the values to the database and validating over there. Is there any particular reason why you are doing what you are doing?
|||Indeed. A better way would be to create a stored procedure that accepts two parameters, the username and password, and then returns fields if those two are matched. Eg.


CREATE PROCEDURE dbo.CheckLogin
@.Username VarChar(50),
@.Password VarChar(50)
AS
SET NOCOUNT ON

SELECT FirstName, LastName FROM users WHERE username = @.Username AND Password = @.Password
GO

This will return no rows if credentials match and one row if credentials are validated (if you get back more than one row then something is wrong with your database design!)

No comments:

Post a Comment