I am not very familiar with PDO, but there is a difference between “prepared operations” and escaped strings. Escaping is the removal of forbidden character strings from a query, but prepared statements tell the database roughly what query to expect .
The request has several parts
Think of it this way: when you query a database, you tell it a few separate things. One may be, for example, "I want you to make a choice." Another could be "limit it to WHERE strings, username is next value".
If you create a query as a string and pass it to the database, it does not know about any part until it receives the filled string. You can do it:
'SELECT * FROM transactions WHERE username=$username'
When he receives this string, he must parse it and decide that "this is SELECT with WHERE ".
Confusing details
Suppose a malicious user enters their username as billysmith OR 1=1 . If you are not careful, you can put this on your line, resulting in:
'SELECT * FROM transactions WHERE username=billysmith OR 1=1'
... which will return all transactions for all users , because 1 is always equal to 1. Oops, you were hacked!
See what happened? The database did not know what parts to expect in your query , so it just parses the string. Not surprisingly, WHERE had an OR , with two conditions that could satisfy it.
Keeping parts straight
If he knew what to expect , namely, SELECT , which WHERE had only one condition, the attacker could not deceive him.
With a prepared expression, you can give it the correct expectation. You can tell the database "I am going to send you a SELECT , and it will be limited to the lines WHERE username = line I am going to give you. All of this - there are no other parts for the query. Are you ready? OK, here comes the line for comparison with the name user. "
With this expectation, the database will not be fooled: it will return rows where the username column contains the actual row "billysmith OR 1 = 1". If no one has this username, he will not return anything.
Other benefits of trained operators
In addition to security benefits, prepared statements have several speed advantages:
- They can be reused with different parameters, which should be faster than creating a new query from scratch, because the database already knows what you want to ask. He has already built a "request plan."
- Some databases (Postgres is one, I think) will begin to plan the query as soon as they receive the prepared statement - before you actually send the parameters for use with it. Thus, you can see acceleration even at the first request.
For another explanation, see Theo's answer here .