What Is SQL Injection? Web Security Explained
SQL injection (SQLi) is a web security vulnerability where an attacker inserts malicious SQL code into an input field that is unsafely included in a database query. It is consistently ranked in the OWASP Top 10 and can lead to data theft, data modification, authentication bypass, and in some configurations, remote code execution.
How SQL Injection Works
Consider: SELECT * FROM users WHERE username = '$input'. If input is ' OR '1'='1, the query becomes: SELECT * FROM users WHERE username = '' OR '1'='1'. This returns all users. A login bypass variant: username = admin'-- comments out the password check entirely. Union-based injection extracts data from other tables: ' UNION SELECT username, password FROM users--.
Prevention: Parameterised Queries
The correct fix is always to use parameterised queries (prepared statements): the SQL structure is defined separately from the data, so user input is never interpreted as SQL syntax. Example (Node.js): db.query('SELECT * FROM users WHERE username = ?', [userInput]). ORM frameworks typically do this automatically. Input validation and escaping are insufficient defences on their own.
Beyond Classic SQLi
Blind SQL injection: the attacker infers information from behaviour (response time, error messages) without seeing output data — harder to exploit but equally dangerous. Second-order injection: malicious input is stored and later unsafely used. NoSQL injection targets MongoDB, Redis, and similar databases with their own query formats. Always treat all user input as untrusted.