Using Parameters in LIKE Statements for SQL
Problem Statement:
While creating a search function, a query using parameters to prevent SQL injection attacks is implemented:
SELECT * FROM compliance_corner WHERE (body LIKE '%@query%') OR (title LIKE '%@query%')
However, this query doesn't return any results.
Answer:
Parameters can be effectively used in LIKE statements to prevent SQL injection attacks. However, the syntax used in the original query is incorrect.
Corrected Syntax:
The correct syntax to use parameters with the LIKE statement is:
SELECT * FROM compliance_corner WHERE (body LIKE @query) OR (title LIKE @query)
In this case, the parameter is defined as "@query" and its value should be assigned using a parameterized query.
Example in VB.NET:
Dim cmd As New SqlCommand( "SELECT * FROM compliance_corner" _ + " WHERE (body LIKE @query )" _ + " OR (title LIKE @query)") cmd.Parameters.Add("@query", "%" + searchString + "%")
The above is the detailed content of How Can I Correctly Use Parameters in SQL LIKE Statements to Prevent SQL Injection?. For more information, please follow other related articles on the PHP Chinese website!