SQL Injection: Anatomy of a Vulnerability
📂 Cybersecurity

SQL Injection: Anatomy of a Vulnerability

⏱ Read time: 11 min 📅 Published: 09/03/2026

💡 Quick Tip

Remember: Never trust user input. Always sanitize your data.

What is SQL Injection (SQLi)?

SQL Injection is a data manipulation technique that occurs when an attacker manages to insert malicious SQL code into a query through application input fields. If the application does not correctly filter this data, the database engine will execute the attacker's code as a legitimate instruction. It is historically one of the most critical vulnerabilities because it allows massive data theft.

Types of SQLi Attacks

  1. In-band (Classic): The attacker uses the same communication channel to launch the attack and see results (e.g., SQL errors revealing table names).
  2. Inferential (Blind): The attacker doesn't see data directly but asks "yes or no" questions to the database (e.g., "does the admin password start with A?") and observes the web response or load time.
  3. Out-of-band: The attacker forces the database to make an external connection (HTTP or DNS) to extract data.

Technical Prevention: Prepared Statements

The only definitive defense is the use of Prepared Statements with bound parameters. In this model, the SQL query is sent first to the database server to be "pre-compiled" with placeholders (?). User data is sent later as pure parameters, so the database engine never interprets them as code.

📊 Practical Example

Real-World Scenario: Fixing a Vulnerable Search Form in PHP

Step 1: Identifying the flaw. The current code concatenates variables: $db->query("SELECT * FROM products WHERE name = '" . $_GET['search'] . "'");. Searching for x'' OR 1=1 -- returns the entire database.

Step 2: PDO Implementation. Change the code to use PHP's PDO object: $stmt = $pdo->prepare('SELECT * FROM products WHERE name = ?'); $stmt->execute([$_GET['search']]);.

Step 3: Verification. Now, if the attacker injects ' OR 1=1, the database looks for a product literally named "' OR 1=1". Since it doesn't exist, the attack fails.

Step 4: Defense in Depth. Complement this with a WAF (Web Application Firewall) to detect suspicious SQL patterns in incoming requests.