What is SQL injection and how do you prevent it?
SQL Injection is a type of attack where an attacker inserts or manipulates malicious SQL
code into a query, which can compromise the database. It usually happens when user input
is improperly sanitized or validated.
Prevention techniques:
Use Prepared Statements/Parameterized Queries: This ensures that user input is treated
as data, not executable code.
- - Example in MySQL (using PDO in PHP)
$stmt = $pdo->prepare('SELECT * FROM users WHERE username =
:username AND password = :password');
$stmt->execute(['username' => $username, 'password' => $password]);
- Input Validation: Always validate user input by checking for expected data types,
lengths, and ranges.
- Escaping User Input: If parameters cannot be parameterized, make sure all user
input is properly escaped.
- Least Privilege Principle: Limit database user permissions to only those necessary
to perform their tasks.
- Web Application Firewalls (WAF): Use WAFs to detect and block SQL injection
attacks.