SQL Injection: Detection, Analysis & Prevention Guide
Table of Contents
🚨 How SQL Injection Happens
SQL Injection (SQLi) is one of the most dangerous and common vulnerabilities in web applications. It allows attackers to manipulate SQL queries by injecting malicious input. Understanding SQLi means understanding how untrusted input flows into dangerous functions—and how to stop it.
Real-world Impact
SQL injection vulnerabilities have led to major data breaches affecting millions of users, resulting in reputational damage, regulatory fines, and legal consequences. Companies have faced losses in the millions due to a single well-executed SQL injection attack that exposed customer data or financial information.
At its core
SQL Injection occurs when: 1) User input is directly inserted into an SQL query. 2) That query is executed by the database without proper sanitization or parameterization.
Vulnerable Code Example
1# ⚠️ Vulnerable code
2username = request.GET["username"]
3query = "SELECT * FROM users WHERE username = '%s'" % username
4cursor.execute(query)
If username is admin' --, the final query becomes: SELECT * FROM users WHERE username = 'admin' --'. The attacker logs in without a password.
What part of the code above is the sink? What part is the source?
Interactive SQL Injection Payload Demo
Select a query template or create your own:
Enter a malicious input or choose an example:
Resulting query (injected parts highlighted):
SELECT * FROM users WHERE username = 'admin' --' AND password = 'user_password'
Notice how the injected payload changes the query's structure, allowing attackers to bypass authentication or execute arbitrary SQL commands.
SQL Injection Attack Flow
admin' --
Direct SQL execution
Unintended data access
Data disclosure
Unauthorized access
Data corruption
🧨 What are Sinks?
A sink is any function or method that executes a query using data. If that data is attacker-controlled, the sink becomes dangerous.
Common SQL Injection Sinks
Language | Sink Function(s) |
---|---|
Python (psycopg2, MySQLdb) | cursor.execute, cursor.executemany |
PHP (PDO, MySQLi) | $pdo->query, $pdo->exec, mysqli_query |
Java (JDBC) | Statement.executeQuery, Statement.executeUpdate |
Node.js (mysql, pg) | connection.query, pool.query |
Ruby (ActiveRecord) | find_by_sql, where with interpolation |
C# (ADO.NET) | SqlCommand.ExecuteReader, .ExecuteNonQuery |
Match the SQL Injection Sinks to Their Languages
Drag each SQL sink function to its corresponding programming language category