What would be the best way to stop SQL injection with a LIKE statement? So here is a example of the code:
string search = Server.HTMLDecode(userEnteredSearchText);
SqlCommand comm = new SqlCommand("SELECT Result WHERE (Keyword LIKE '%" + @search + "%') "
comm.Parameters.Add(new SqlParameter("search", search));
This is what I have been doing other sql statements and it seems like special characters such as ' and % can’t break those statements, but I’m guessing with a LIKE statement you need to do a escape key or something?
Sorry the quotes are off. You do it precisely like you do with everything else, except that within the SQL you need to concatenate the
%‘s. Also,HTMLDecodeis probably not doing you any good here at all, right? What if they want to search in the db for things that contain"&"So in your example, you were closing the SQL literal to put in
@search, which is an invalid keyword or variable – you just need to leave that inside the SQL statement. Other DB’s, you need toCONCATthe things together. But the bind variable will properly escape the stuff going to the driver.