It shows invalid user credentials even though I inputted the right one. I don't know if I made the parameters wrong or if my query is wrong. I want to learn about parameterized queries but I don't know what I'm doing wrong here.
con.OpenConnection();
using (con.connection)
{
String query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
try
{
MySqlCommand cmd = new MySqlCommand(query, con.connection);
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
MessageBox.Show("Invalid user credentials.");
}
else
{
//Do stuff
}
}
catch (MySqlException mse)
{
MessageBox.Show(mse.Message);
}
finally
{
con.CloseConnection();
}
Not sure why it is not working but if you use AddWithValue, it will work. Something like this
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
Change your code so that it's calls a method, when you click on a Button, pass the Username and Password variable into this Method. Create a AutoProperty for UserName and Password at the Class Level
private DataTable PopulateSomeDatatSet(DataSet aDataset, string UserName, string Password)
{
var query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
MySqlDataAdapter sda;
using (SqlConnection connStr = new SqlConnection(ConnString)) //replace with your ConnectionString Variable
{
using (MySqlCommand cmd = new MySqlCommand(query, connStr))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = UserName;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = Password;
sda = new MySqlDataAdapter(cmd);
new MySqlDataAdapter(cmd).Fill(aDataset);
}
}
((IDisposable)sda).Dispose();
return aDataset.Tables[0];
}
Related
This is my code
I don't know what's my fault but it is not checking whether the username exist in database or not.
String connectionString = #"Data Source=localhost; Database=pramod; User ID=itesuser; password=ites; Port=3309;";
MySqlConnection con = new MySqlConnection(connectionString);
con.Open();
String query = "select * from logins where USERNAME=#username and PASSWORD=#password";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox2.Text.Trim());
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
int i = (int)cmd.ExecuteScalar();
if (i == 0)
{
Response.Write("username wrong");
}
if (dt.Rows.Count > 0)
{
Session["username"] = TextBox1.Text.Trim();
Response.Redirect("Dashboard.aspx");
}
else {
Label1.Visible = true;
Label1.Text = "Your password is incorrect";
Label1.ForeColor = System.Drawing.Color.Red;
}
con.Close();
it is checking whether the password is correct or wrong but not the username, now i need to check username and the the password
I think your clue is here:
String query = "select * from logins where USERNAME=#username and PASSWORD=#password";
By doing this, you check the username and password at the same time. So if the username OR the password is incorrect, you get 0 rows in your result.
To get what your want, only mention the username in the SQL query, and if you get a record, you compare the password in .Net code.
So:
String query = "select * from logins where USERNAME=#username";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text.Trim());
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
And then check the password if you get 1 row back.
This looks like an insecure way of handling logins, so I hope you at least will hash and salt the passwords. Now you are one database leak away from a very embarasing situation. https://duckduckgo.com/?q=password+hashing+and+salting
I have a method in DataBase class that resides in App_Code which I use to call a Stored Procedure for Login, but when I make the call I get no error but my Login will not complete.
This is the DataBase Class:
public class DataBaseClass
{
SqlDataAdapter da;
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public DataBaseClass()
{
}
public DataTable CallSP(string UserName, string Password)
{
con = new SqlConnection(#"Data Source=MyServer;Initial Catalog=MyDataBase;Integrated Security=True");
con.Open();
cmd = new SqlCommand("LoginUser", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = "UserName";
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 20).Value = "Password";
da = new SqlDataAdapter(cmd);
da.Fill(dt);
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
return dt;
}
This is the code I used to call for Login:
DataBaseClass dbClass = new DataBaseClass();
dt = new DataTable();
dt = dbClass.CallSP("UserName", "Password");
if (dt.Rows.Count > 0)
{
boolReturnValue = true;
Session["UserId"] = dt.Rows[0]["Id"].ToString();
string updateLastLogin = "Update [User] SET LastLogin='" + System.DateTime.Now.ToString() + "' where Id='" + Session["UserId"].ToString() + "'";
dbClass.ConnectDataBaseToInsert(updateLastLogin);
}
return boolReturnValue;
}
This is My Stored Procedure:
CREATE PROCEDURE [dbo].[LoginUser] (
#UserName nvarchar(20),
#Password nvarchar(20)
)
AS
SET NOCOUNT ON;
(
SELECT * FROM [User] WHERE Email = #UserName AND Password = #Password
)
Can anyone reproduce my code and tell me why my Login call could not work.
Try do the following changes in the CallSP method:
cmd.Parameters.Add("#UserName", SqlDbType.NVarChar, 20).Value = UserName;
cmd.Parameters.Add("#Password", SqlDbType.NVarChar, 20).Value = Password;
Now appling more attention in your code I saw that your parameters are around quotes, so you were passing the literal strings "UserName" and "Password" instead the values.
With this changes you will pass the values from your parameters.
Sorry by my mistakes.
I hope it can help you.
I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}
I am trying to run a SQL query based on who's logged in which gets the Team_ID and assigns it to the session variable. I am having trouble assigning the result to the variable.
protected void ButtonLogin_Click(object sender, EventArgs e)
{
//check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Team_User where Email = #username and Password_1 = #password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlCommand cmdID = new SqlCommand("select Team_ID from Team_User where Email = #username and Password_1 = #password", con);
cmdID.Parameters.AddWithValue("#username", UserName.Text);
cmdID.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlDataReader reader = cmdID.ExecuteReader();
int Team_ID = reader.GetInt32(1);
Session["Team_ID"] = Team_ID;
Response.Redirect("AddPlayer.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
Your code doesn't make a whole lot of sense....
If you only want the Team_ID - why are you loading the whole row first, and then call the database again to get just the Team_ID???
I tried to simplify your code a good bit:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
// check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
// define connection string and SQL query as strings
string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = #username AND Password_1 = #password";
// set up SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// define and fill parameters - DO NOT use .AddWithValue!
cmd.Parameters.Add("#username", SqlDbType.VarChar, 100).Value = UserName.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 100).Value = Password.Text;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
// if we got back a result ....
if(result != null)
{
int teamID = Convert.ToInt32(result.ToString());
Session["Team_ID"] = teamID;
Response.Redirect("AddPlayer.aspx");
}
else
{
// if result is NULL, then the username+password
// were NOT found - do what needs to be done in that case here
}
}
}
}
There is a lot of tutorials regarding parameterized queries but most of them involve using SqlCommand, the only thing my code accepts is SqlDataAdapter for my SQL command, anytime I try to instantiate it as a SqlCommand I get errors.
TL;DR
I either need guidance on how to rework this using parameterized queries or I need to know why my SqlDataAdapter line doesn't work as an SqlCommand line.
private void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Jake\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) From Login Where Username = '" + txtUsername.Text + "' and Password = '" + txtPassword.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
MessageBox.Show("LOGIN!");
}
else
{
MessageBox.Show("FAILED!");
}
}
You can use:
using (SqlDataAdapter sqlDA = new SqlDataAdapter("Select * from user where username = #username and password = #pass", sqlConnect))
{
sqlDA.SelectCommand.CommandType = CommandType.Text;
sqlDA.SelectCommand.Parameters.Add("#username", SqlDbType.Varchar).Value = username;
sqlDA.SelectCommand.Parameters.Add("#pass", SqlDbType.Varchar).Value = password;
sqlDA.Fill(dataTableVariable);
return dataTableVariable;
}
For your password remember to use a hash algorithm
This code is not tested. If you want the best performance you can explore execute scalar.
You can use Parameters.AddWithValue in SqlDataAdapter
sda.SelectCommand.Parameters.AddWithValue("#ParamName",value);
Check this: c# Using Parameters.AddWithValue in SqlDataAdapter
Try using parametrize query, it will avoids errors and sql injection
Once you have the reader you can use HasRow() to check if a record is returned
string conString = "xxxxxxxxxxxxxxxxxxxxxxxx";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (var cmd = new SqlCommand(
"SELECT * FROM Login Where Username=#Username AND Password=#Password",
con))
{
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRow())
{
if(reader.Read())
{
var username = reader["Username"].ToString();
}
}
else
{
//User does not exists
}
}
}
}
You will need to import some library:
using System;
using System.Data;
using System.Data.SqlClient;