49. Introduction to Web Security: SQL Injection Prevention
SQL Injection is one of the most common and dangerous vulnerabilities. It occurs when an attacker inputs malicious SQL code into a web form, which is then executed by the database.
The Vulnerability (Concatenation)
Imagine an attacker inputs this into a login form's username field:
' OR 1=1 --
If we concatenate this directly, the resulting SQL becomes:
sql SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = '...'
The -- makes the rest of the query a comment, and the OR 1=1 is always true, granting unauthorized access.
The Solution: Prepared Statements (Binding)
Prepared statements guarantee that the user input is treated as data only, never as executable SQL code. PDO handles this separation for you.
Unsafe (Avoid!):
php $user_input = $_POST['username']; // DANGEROUS: Concatenating input directly $sql = "SELECT * FROM users WHERE username = '$user_input'";
Safe (Use PDO):
php
prepare($sql); // 2. The bind function ensures user_input is treated as a string value $stmt->bindParam(':user_input', $user_input); $stmt->execute(); // If the attacker inputs ' OR 1=1 --, the database searches for a user // whose username literally equals the string "' OR 1=1 --", which fails. ?>Crucial Rule: Never, ever trust user input. Use prepared statements for every single database query that includes external data.