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
Release: 2024-12-27 07:38:14
Original
201 people have browsed it

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%')
Copy after login

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)
Copy after login

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 + "%")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template