Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does escaping SQL values require an open connection?

Tags:

php

mysqli

Just for clarity, can anyone explain why mysqli_real_escape_string has to read:

$query = mysqli_real_escape_string($conn,"SELECT * FROM tbl");

And not just:

$query = mysqli_real_escape_string("SELECT * FROM tbl");

Thanks for any help!

like image 221
Richard Tinkler Avatar asked Oct 15 '13 15:10

Richard Tinkler


People also ask

How does escape work in SQL?

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.

How do I escape a SQL query string?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

Why do you need to use escape characters in strings?

It is used in character strings to indicate that the current line of source code continues on the next line. The value of an escape sequence represents the member of the character set used at run time.

How do I escape in SQL Server?

In ANSI SQL, the backslash character (\) is the escape character. To search for data that begins with the string \abc , the WHERE clause must use an escape character as follows: ... where col1 = '\\abc';


1 Answers

Because of charset encoding.

Without the $conn, mysqli_real_escape_string() won't be able to detect which character encoding the connection is using, and will blindly try to escape common dangerous characters - leaving some potentially dangerous charset hacks to go through.

True (not emulated) prepared statements are even better (or more secure, as you prefer), as they take the character encoding of the column instead of the connection into account.

like image 103
Alix Axel Avatar answered Oct 05 '22 02:10

Alix Axel