Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I need to escape when sending a query?

Tags:

When you execute a SQL query, you have to clean your strings or users can execute malicious SQL on your website.

I usually just have a function escape_string(blah), which:

  • Replaces escapes (\) with double escapes (\\).
  • Replaces single quotes (') with an escaped single quote (\').

Is this adequate? Is there a hole in my code? Is there a library which can do this quickly and reliably for me?

I'd like to see graceful solutions in Perl, Java, and PHP.

like image 270
andrewrk Avatar asked Aug 05 '08 18:08

andrewrk


People also ask

How do you escape a query?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.

What does it mean to escape a SQL query?

Escape sequences are used within an SQL statement to tell the driver that the escaped part of the SQL string should be handled differently. When the JDBC driver processes the escaped part of an SQL string, it translates that part of the string into SQL code that SQL Server understands.

What does it mean to escape data?

Escaping data is the process of securing output by stripping any unwanted data such as script tags, incorrectly formed HTML and other unwanted data. It therefore prevents of this data being seen or executed as code.

What characters need to be escaped SQL?

The escape character (\) needs to be escaped as (\\). The single quote (') needs to be escaped as (\') or ('') in single-quote quoted strings. The double quote (") needs to be escaped as (\") or ("") in double-quote quoted strings. The wild card character for a single character (_) needs to be escaped as (\_).


2 Answers

For maximum security, performance, and correctness use prepared statements. Here's how to do this with lots of examples in different languages, including PHP:

https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks

like image 113
Mark Harrison Avatar answered Oct 16 '22 19:10

Mark Harrison


I would also escape comments (double dash)

--
like image 33
GateKiller Avatar answered Oct 16 '22 17:10

GateKiller