SyntaxStudy
Sign Up
Web Security Understanding SQL Injection Attacks
Web Security Beginner 1 min read

Understanding SQL Injection Attacks

SQL injection (SQLi) is a code injection technique where an attacker inserts malicious SQL syntax into an input field that is then concatenated directly into a database query. Because the database cannot distinguish between the intended query structure and the injected payload, it executes the attacker's commands. SQL injection has topped security vulnerability charts for over two decades and regularly appears in high-profile breaches involving millions of leaked credentials. The classic example is a login form that builds the query `SELECT * FROM users WHERE username='{input}' AND password='{input}'`. Supplying the username `admin'--` comments out the password check, granting access without a valid password. More destructive payloads use UNION SELECT to extract data from other tables, stacked queries with semicolons to modify or delete data, or time-based blind injection to exfiltrate data one bit at a time through response delays. SQL injection vulnerabilities exist in every database engine — MySQL, PostgreSQL, SQL Server, SQLite, Oracle — and in every language that builds queries through string concatenation. Second-order injection is particularly insidious: the payload is safely stored in the database on first insertion but later read back and unsafely interpolated into another query. Automated scanners like sqlmap can detect and exploit SQLi vulnerabilities, so attackers do not need deep expertise.
Example
<?php
// VULNERABLE code — never do this

// User submits: username = admin'--
// Resulting query: SELECT * FROM users WHERE username='admin'--' AND password='...'
// The -- comments out the password check → authentication bypass

$username = $_POST['username'];
$password = $_POST['password'];

// BAD: direct string interpolation
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);

// ----------------------------------------------------------------
// Attack examples (what the attacker sends):
// ----------------------------------------------------------------
// 1. Auth bypass:      username = admin'--
// 2. UNION exfiltrate: username = ' UNION SELECT null,username,password FROM users--
// 3. Drop table:       username = '; DROP TABLE users;--
// 4. Blind time-based: username = ' AND SLEEP(5)--

// ----------------------------------------------------------------
// Why this is dangerous:
// ----------------------------------------------------------------
// SELECT * FROM users
//   WHERE username='' UNION SELECT null,username,password FROM users--'
//   AND password='...'
// → Returns ALL usernames and password hashes from the users table.