Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is using a mysql prepared statement more secure than using the common escape functions?

There's a comment in another question that says the following:

"When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string."

Source

So, what i want to ask is: Why are prepared parameterized queries more secure?

like image 542
João Josézinho Avatar asked Apr 09 '09 02:04

João Josézinho


People also ask

Why are prepared statements more secure?

Prepared statements can help increase security by separating SQL logic from the data being supplied. This separation of logic and data can help prevent a very common type of vulnerability called an SQL injection attack.

What is the advantage of using PreparedStatement over statement?

Some of the benefits of PreparedStatement over Statement are: PreparedStatement helps us in preventing SQL injection attacks because it automatically escapes the special characters. PreparedStatement allows us to execute dynamic queries with parameter inputs.

Are prepared statements Safe?

Well simply using PreparedStatement doesn't make you safe. You have to use parameters in your SQL query which is possible with PreparedStatement .

Which is faster statement or PreparedStatement?

Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.


1 Answers

An important point that I think people here are missing is that with a database that supports parameterized queries, there is no 'escaping' to worry about. The database engine doesn't combine the bound variables into the SQL statement and then parse the whole thing; The bound variables are kept separate and never parsed as a generic SQL statement.

That's where the security and speed comes from. The database engine knows the placeholder contains data only, so it is never parsed as a full SQL statement. The speedup comes when you prepare a statement once and then execute it many times; the canonical example being inserting multiple records into the same table. In this case, the database engine needs to parse, optimize, etc. only once.

Now, one gotcha is with database abstraction libraries. They sometimes fake it by just inserting the bound variables into the SQL statement with the proper escaping. Still, that is better than doing it yourself.

like image 153
MadCoder Avatar answered Sep 23 '22 02:09

MadCoder