Web Security
Beginner
1 min read
Understanding SQL Injection Attacks
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.
Related Resources
Web Security Reference
Complete tag & property list
Web Security How-To Guides
Step-by-step practical guides
Web Security Exercises
Practice what you've learned
More in Web Security