Lesson 4.1: SQL injection
What happens when a visitor's input is glued into a database query: the input stops being data and becomes part of the SQL. Error messages that give away the database, conditions that are always true, and UNION queries that pull other tables into the page. And the fix that works every time: parameterised queries (prepared statements), where the query and the data travel separately. In the lab the shop's product page builds its SQL from the URL. You confirm the injection, see a UNION query print user names and password hashes, find the line, rewrite it with PDO prepare and execute, and prove that the same attacks now return nothing while the page still works.
20 min
You will learn to
- Explain how SQL injection happens
- Recognise error-based, boolean and UNION injection
- Find string-built queries in PHP code
- Fix them with prepared statements (PDO prepare/execute)
- Explain why escaping and blocklists are not enough
Key terms
- SQL
- Structured Query Language, the language used to read and change data in relational databases.
- Injection
- Untrusted input is interpreted as code or commands by some interpreter: a database, a browser, a shell.
- SQL injection (SQLi)
- Input that changes the structure of a database query because the query was built by joining strings.
- UNION
- SQL keyword that appends the rows of a second SELECT to the first.
- Prepared statement
- A query sent to the database with placeholders (?) and the values sent separately, so values are never parsed as SQL.
- Least privilege (database)
- The application's database account may do only what the application needs.
← Ports and sockets: which program gets the data · All lessons · Common attacks: phishing, malware, password attacks, denial of service →