Explorer
SQL

What is SQL Injection?

What is SQL Injection?

SQL Injection (SQLi) occurs when untrusted user input is directly concatenated into a dynamic SQL statement, allowing attackers to execute arbitrary database queries.

Vulnerable vs Secure Implementation

CODE
-- ❌ VULNERABLE: Direct string concatenation
SELECT * FROM users WHERE username = '' OR '1'='1' --' AND password = '';

-- ✅ SECURE: Parameterized Query (Prepared Statement)
SELECT * FROM users WHERE username = $1 AND password = $2;

Defensive Measures

  • Parameterized Queries: The database compiles the query structure first; input values are bound strictly as data literals and cannot alter the query syntax tree.
  • Least Privilege: Ensure application database connections only possess minimal necessary permissions.
  • Object-Relational Mappers (ORMs): Use ORMs that parameterize queries automatically.

Finished this lesson?

Mark this chapter complete to update your learning streak and unlock the next lesson.