I’ve come os far as to gaining basic understanding of prepared statements and I get that they prevent SQL-injection attacks. But I have yet to understand WHY they protect against said attacks. I know there are similar questions asked but I didn’t find the answers entirely satisfying.
Example – very unsafe code
So here we have the most basic way to communicate with our database:
$query = "SELECT * FROM users where id=$username";
Without any protection, a user can input malicious code and thus “trick” the database engine to execute a devastating query:
$username = "1; DROP TABLE users;"
SELECT * FROM users where id=1; DROP TABLE users;
What I don’t understand is how a prepared statement manages to “filter out” such data. What is the mechanic behind it that does NOT lure the database to generate such a SQL-query as shown above? Is just as simple as escaping certain characters, like semicolon in the example above, or is it more complicated?
If I was to do the exact injection attack as in the example, but running it through a prepared statement, what kind of command string would reach the database engine?
Prepared statements don’t just add in the text, they send it as data, and let the database process it separately. Because in reality the database doesn’t actually use the SQL statements, it uses “compiled” versions of them.
Not quite sure I was clear, but it lies in how the query is sent to the database.