Reputation: 85
I'm trying to create a login field using ASP.NET which will take input from the textbox fields and check them against the "user" table in my database. The columns are User ID
and Password
. But an error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '`'
appears when the login form is used. I don't see any issue with the syntax...
I'm new to this so please excuse me if the error is obvious!
public partial class Login_Page : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblErrorMessage.Visible = false;
SqlConnection con = new SqlConnection("Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True");
con.Open();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True";
con.Open();
string userid = txtUsername.Text.Trim();
string password = txtPassword.Text.Trim();
SqlCommand cmd = new SqlCommand("select `user id`,`password` from user where `user id`='" + txtUsername.Text + "'and `password`='" + txtPassword.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["username"] = txtUsername.Text.Trim();
Response.Redirect("Homepage.aspx");
}
else
{
lblErrorMessage.Visible = true;
}
con.Close();
}
}
Upvotes: 3
Views: 34777
Reputation: 30565
there are many issues with your code :
`
is not SQL Server Syntax..
using (SqlCommand cmd = new SqlCommand("select 1 from tbl where id=@id", conn))
{
var idParameter = new SqlParameter()
idParameter.ParameterName = "@id";
idParameter.Value = 1234;
cmd.Parameters.Add(idParameter);
....
}
using(SqlConnection conn = new SqlConnection())
.
Upvotes: 2
Reputation: 34150
Just remove the '`' characters to make it work.
Your code is vulnerable to injection try to add values with SqlCommand.Parameters.Add()
method.
Use this code:
SqlCommand cmd = new SqlCommand("select userid, password from user where user id = @id and password = @password", con);
cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = txtPassword.Text;
And as @marc_s mentioned, user id
is not a valid column name, it should be like userid
or if it has space in it is should be like: [user id]
Upvotes: 6