0

is this the correct statement if not plz help me correct it.

String query = "delete from favourite where username=" + 
               Session["username"].ToString() + "and id=" + id;
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Kunal Bagam
  • 13
  • 1
  • 5
  • 1
    No, this is not correct. You need to [use parameters](https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements). – Dour High Arch Sep 09 '19 at 17:42
  • **Always use parameterized sql and avoid string concatenation** to add values to sql statements. See [How can I add user-supplied input to an SQL statement?](https://stackoverflow.com/q/35163361/1260204), and [Exploits of a Mom](https://xkcd.com/327/). – Igor Sep 09 '19 at 17:44
  • so i have to use cmd,parameters.addwithvalue() and specify parameters there? – Kunal Bagam Sep 09 '19 at 18:09
  • Follow instructions of [the accepted answer](https://stackoverflow.com/a/7505842/22437); it does not use `AddWithValue` and specifically says to not use it. – Dour High Arch Sep 09 '19 at 18:18
  • i used AddWithValue() method and it worked. Thanks guys! – Kunal Bagam Sep 09 '19 at 18:49

1 Answers1

0

If your question is purely about SQL, then yes, what you have will work. But, as you have it, you have a very serious security problem. Google "SQL injection attacks". I'm not sure what you are using for data access (ADO.NET? Entiry Framework? Dapper?) But regardless, you'll want to use parameters:

var sql = "delete from favourite where username=@username and id=@id";

and then:

cmd.Parameters.AddWithValue("@username", Session["username"].ToString());
cmd.Parameters.AddWithValue("@id", id);

But even then, AddWithValue isn't the best way, because it can cause type conversion issues once the query hits the database. You are better off doing it longhand:

var userNameParam = new SqlParameter("username", SqlDbType.VarChar);
userNameParam.Value = Session["username"].ToString();

var idParam = new SqlParameter("id", SqlDbType.Int);
idParam .Value = id;

command.Parameters.Add(salaryParam);
command.Parameters.Add(idParam );
Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • Thank You sir! It worked after using Parameters.AddWithValue() method. – Kunal Bagam Sep 09 '19 at 18:48
  • You don't need to worry about SQL injection attacks if the input is not coming directly from the user or input is coming from something like a drop down list where values are controlled. – Dominic Isaia Sep 09 '19 at 19:15
  • 1
    @DominicIsaia, I disagree. Items in a dropdown list can easily be spoofed. And even if the input is not coming "directly" from the user, it is almost ways going to come indirectly from a user, and the injection attack inputs are still possible. – Casey Crookston Sep 09 '19 at 19:32