Home >Database >Mysql Tutorial >How Can I Correctly Use Parameters in SQL LIKE Statements to Prevent SQL Injection?

How Can I Correctly Use Parameters in SQL LIKE Statements to Prevent SQL Injection?

Linda Hamilton
Linda HamiltonOriginal
2024-12-27 07:38:14246browse

How Can I Correctly Use Parameters in SQL LIKE Statements to Prevent SQL Injection?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn