I have a site that allows users to search the database for several items. However I am not that good with SQL and I have read that allowing user to type in boxes that then use "SELECT-statements" is not safe. Code below:
Search-button sends search as parameter:
protected void search_click (object sender, EventArgs e)
{
Response.Redirect("Search.aspx?Result=" + TextBoxSearch.Text);
}
onLoad in my search-page it gets the value and calls getData():
search = Request.QueryString["Result"].ToString();
getData();
getData() method:
protected void getData()
{
using (SqlConnection con = new SqlConnection(strCon))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT [categoryId], [category] FROM [Category] WHERE ([category]=@search)";
cmd.Parameters.AddWithValue("@search", search);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
LabelCat.Text = reader.GetString(reader.GetOrdinal("category"));
HiddenFieldID.Value = reader.GetInt32(reader.GetOrdinal("categoryId")).ToString();
}
else
{
LabelCat.Text = "Add"; //When search is made but no cateogry found
}
}
}
con.Close();
}
}
Is this safe? I feel like it is very weak against sql-injections but then again I don't know much about that. If it's not safe, please suggest a safe way I can do this.
I am building my application in VS12 using ASP.NET and C# webforms. Building my database using SQL management studio.
EDIT: Eventually I will have to search several tables here using join-statements, don't know if that is relevant but thot I should mention it.