SQL Injection is when malicious SQL is inserted through user input.
Prevention
- Use prepared statements with parameterized queries
- Validate and sanitize input
- Use stored procedures
- Apply least privilege principle
SQL Injection is when malicious SQL is inserted through user input.
-- VULNERABLE (never do this!) SELECT * FROM users WHERE email = '$input'; -- SAFE: Prepared statement PREPARE stmt FROM "SELECT * FROM users WHERE email = ?"; SET @email = "user@mail.com"; EXECUTE stmt USING @email; -- In PHP (PDO) $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email"); $stmt->execute(['email' => $input]);
-- DANGEROUS (never do this): -- SELECT * FROM users WHERE email = "$email" -- Use prepared statements (PDO): -- $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); -- $stmt->execute([$email]); -- Escape user input SELECT * FROM users WHERE email = "alice@example.com" AND password = SHA2("rawsecret", 256); -- Validate with CHECK constraints CREATE TABLE login_attempts ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(150), IP VARCHAR(45), attempted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX (email, attempted_at) );
Why is concatenating user input into SQL dangerous?
Users can inject SQL commands. Always use prepared statements with parameterized queries.
Best protection against SQL injection?
Prepared statements separate SQL logic from data.
The SQL structure is compiled first, then data is bound separately. User input is never interpreted as SQL code.