SQL Injection Explained: Testing in Labs and Prevention

SQL Injection Explained: Testing in Labs and Prevention
✨ AI Summary

⏱️ 60 min · Beginner · 1 hands-on lab

Picture a login page on a practice app you are allowed to break. You type a single quote into the username box and the page throws a strange database error instead of a polite "wrong password". That small slip is how sql injection usually announces itself, and it tells you the developer glued your input straight into a query.

In this Tutorial I will walk you through exactly that, but only against the SecurityElites practice lab and your own machine. We will look at why the flaw exists, how in-band, blind and out-of-band variants differ, and how to test a login form safely.

Then we switch sides. I will show you how to spot injectable code in a review, fix it with parameterized queries, handle the parts parameters cannot cover, and retest to prove the hole is closed.

🎯 What You Will Be Able to Do

Explain how sql injection turns untrusted data into query syntax
Test a login form for sql injection in an intentionally vulnerable lab
Tell in-band, blind and out-of-band sql injection apart
Spot injectable code and fix it with parameterized queries
Apply allow-lists and least privilege where parameters cannot help
Explain why WAFs, escaping, stored procedures and ORMs are not complete fixes

βœ… Before You Start

  • Basic understanding of how web forms and HTTP requests work
  • Very basic SQL: SELECT, WHERE, AND, OR
  • A browser, and optionally a web proxy such as Burp Suite

SQL injection in plain words: the direct answer

I'll give you the short answer first, then we build it up. SQL injection happens when untrusted data becomes part of a query's SQL syntax [1]. The database cannot tell what the developer meant as a command and what the user typed as a value, so it runs all of it.

The main fix is just as short. Define the SQL structure separately from the data values, then bind the values through the database API [1]. This is called parameter binding. The user's input is only ever treated as a value, never as code.

This is not an old problem that has gone away. In the OWASP Top 10:2025, injection is category A05:2025, down from third place in the previous edition, and SQL injection sits inside it alongside NoSQL injection, OS command injection and XSS [8]. That Top 10 was released on 6 November 2025 [10]. In 2026, CISA added SQL injection flaws in Fortinet FortiClient EMS (CVE-2026-21643) and Metabase (CVE-2026-72898) to its Known Exploited Vulnerabilities catalog [15][17].

This page is part of our wider path. If you are new to the field, start with the ethical hacking roadmap to see where this skill fits.

πŸ’‘ Tip: Hold on to one sentence: the fix is to separate structure from values. Everything later on this page, from labs to code review, comes back to it.

What SQL injection is and how it works

Let me show you why this flaw exists. SQL statements mix data with commands in the same string [19]. A crafted input can leave the data context and enter the command context. That jump is the whole vulnerability.

Picture a login page. The developer builds the query by gluing the typed username and password into a string. Here is the vulnerable pattern in pseudo-code, which you will only ever see on your own machine or in a lab.

VULNERABLE PATTERN (ILLUSTRATION)
# Server-side code, string concatenation: do not write this
query = "SELECT * FROM users WHERE username = '" + user + "' AND password = '" + pw + "'"

User input is pasted straight into the SQL text.

🧭 Walking through the flaw

Step 1 β€” Normal inputA user types alice and secret. The query becomes WHERE username = 'alice' AND password = 'secret'. Every typed character stays inside the quotes, so it is data.
Step 2 β€” Input with a quoteIf the user types a single quote, it closes the string early. The text after it is no longer inside quotes, so the database reads it as SQL syntax.
Step 3 β€” Logic changesOnce input is read as syntax, the person typing can change what the WHERE condition means. The developer's intended check is no longer the check that runs.
Step 4 β€” Why it happensThe code built one flat string. The database receives text only, with no record of which parts were meant as values.

We will test this safely in a lab later. For now, understand the mechanism, because every type of sql injection is a variation on that quote breaking out of its context.

🧠 Quick check

What makes the concatenated query vulnerable?

Threat model: what an attacker can reach

Now let's think about impact. What a successful sql injection can do depends on database features and privileges. OWASP lists reading data, modifying it, running administration operations such as shutting down the DBMS, and reading or writing files. In some cases it can run operating system commands [2].

So who is the attacker? Often anyone who can reach the page. The Metabase flaw let a remote attacker inject arbitrary SQL queries without authentication [17]. Entry points are any place the application takes input and uses it in a query: login and search forms, URL parameters, and also headers or cookies if the code uses them.

It is still in advisories because the mistake is easy to make. CISA's 2026 weekly bulletins list many new SQL injection flaws, several where user-controlled parameters were concatenated or interpolated into SQL without parameterization or escaping [18]. CISA also described this vulnerability type as a frequent attack vector for malicious actors when it added a Cisco Secure Email Gateway flaw [16]. CISA and the FBI have also called it a still-prevalent class of vulnerability [19].

It helps to keep it separate from its relatives. Here the interpreter is the database. In command injection the interpreter is the operating system shell, and in server-side template injection it is a template engine. Same root idea, different target.

⚠️ Watch out: Only test systems you own or have written permission to test. Practise in intentionally vulnerable labs. Probing a real site without authorisation is illegal, even if you mean no harm.

Types of sql injection: in-band, blind and out-of-band

Here is the key point: sql injection is not one trick. It is a family of techniques, and the type you meet depends on what the application shows you back. Testers sort them by how the answer reaches you: in the same response, by inference, or through a separate channel. Let me walk you through each one at concept level, with no attack strings, so you know what you are looking for when we reach the lab.

πŸ“– Words I just used

In-bandYou send the input and read the result in the same page or response.
BlindThe page shows no data or errors, so you infer the answer from how the application behaves.
Out-of-bandThe database sends the result over a different channel, such as a network request to a server the tester controls.

In-band is the easiest to spot. Two common forms exist. Error-based relies on the database error appearing in the page. UNION-based lets the tester append a second query so its results are displayed alongside the normal ones, for example in a product list.

Blind comes in two flavours. With boolean-based testing, you ask the database a true or false question and watch whether the page changes, perhaps a result appears or vanishes. With time-based testing, the page looks identical either way, so you ask the database to pause and measure how long the response takes.

Out-of-band is for cases where even timing is unreliable. The database is made to trigger an external lookup or request. The PortSwigger Web Security Academy path covers all of these, and its out-of-band labs need Burp Suite Pro features such as Collaborator. That is why I will not ask you to do them today.

⚠️ Watch out: Verbose errors are a gift to an attacker. In the Web Security Academy visible error-based lab, a detailed database error exposes the full SQL query and shows the injection sits inside a single-quoted string. Never show raw database errors to users in production. Log them server-side and return a generic message.

🧠 Quick check

A page looks identical for every input, but one test makes the response take several seconds longer. Which type is this most likely?

Before you type a single quote into anything, let me set the ground rules. Testing for sql injection against a system you do not own, and have no written permission to test, is illegal in many places, even if you only look. So we practise in two kinds of place only: intentionally vulnerable labs, and targets where the owner has explicitly authorised you in writing.

β˜‘οΈ Authorisation rules I follow

For practice, I point you to two places. The SecurityElites lab below is a mock webmail called MiniMail with a login page you can break safely. The free PortSwigger Web Security Academy offers a login bypass lab and a product-category filter lab, among many others.

Now prepare your tools. You need a browser and an intercepting proxy, which is a program that sits between the browser and the site so you can see and edit each request. Burp Suite is the usual choice, and the ethical hacking roadmap points you to the right tutorial. Set the browser to send traffic through the proxy, normally 127.0.0.1 on port 8080, then check that a request appears in the proxy history.

PROXY CHECK
Confirm your proxy is listening on your own machine
curl -I -x http://127.0.0.1:8080 http://localhost:8000
HTTP/1.0 200 OK
The request should also show up in the proxy history

Start any simple web server on your own machine first, for example python3 -m http.server 8000. If curl says connection refused, start the proxy and check the listener port.

πŸ’‘ Tip: Use a separate browser profile for testing. It keeps proxy settings and test cookies away from your everyday browsing.
πŸ§ͺ HANDS-ON LAB Β· BEGINNER Β· 20 MIN Β· SECURITYELITES LAB
SQL Injection β€” Login Bypass

This is the lab we use for the demo next. Open it now and get comfortable before we test it together.

What to try
β–Έ Load the MiniMail login page with your proxy running
β–Έ Submit a normal wrong login and study the response in the proxy history
β–Έ Note which fields the server receives and how the failure looks
β–Έ Think about how the server might build its query from those two fields

What to notice: Whether the error message differs for a wrong username and a wrong password What the request looks like in the proxy, including method and parameters

I start a throwaway web server on my own machine so the proxy check has something to talk to.

LOCAL TEST SERVER
Terminal 1: serve a folder on localhost only
python3 -m http.server 8000 –bind 127.0.0.1
Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) …
Terminal 2: confirm the server answers before adding the proxy
curl -I http://localhost:8000
Confirm the proxy port is open (Burp default 8080)
ss -ltn | grep 8080

The server prints a serving line, curl returns HTTP/1.0 200 OK, and ss shows a LISTEN entry on port 8080 once the proxy is running.


Controlled demo: bypassing a vulnerable login

I am going to run this test with you, step by step, against one place only: the SecurityElites practice lab called SQL Injection, Login Bypass. It is built to be vulnerable. Never repeat these steps on a real site unless you hold written permission from its owner. If you ever find a flaw in a live system you are not authorised to test, stop and report it through the owner's disclosure channel.

The lab app is called MiniMail. Its login page builds a SQL query by joining your username and password into a string. That is the textbook cause of sql injection, so it is a safe place to watch the flaw happen. I will show you the method and the reasoning, and leave the final step for you to work out.

⚠️ Watch out: Only test the lab app, your own localhost setup, or a target you have written authorisation for. Testing anyone else's login form is illegal in many countries, even if you mean no harm.

Detection methodology for testers and reviewers

I want to give you a repeatable method for finding sql injection, because random poking wastes time and can break things. Everything here runs only against your own lab, a deliberately vulnerable practice app or localhost. Testing anything else needs written permission, and if you ever find a flaw in a real system you were not invited to test, report it through the owner's disclosure channel and stop there.

The method has four stages: map, probe, confirm, stop. It works the same whether you are a tester watching responses or a reviewer reading source code. For the wider picture of where this skill fits, see the ethical hacking roadmap.

πŸ—ΊοΈ The detection loop
  1. Map every input
  2. Probe for errors or differences
  3. Confirm with a safe check
  4. Stop at proof
  5. Write it up

🧭 Tester workflow in your own lab

Step 1 β€” Map the inputsList every place data enters: form fields, URL parameters, cookies and headers. Your proxy history is the easiest source. You should end up with a simple table of endpoint, parameter and example value.
Step 2 β€” Probe gentlyChange one parameter at a time. Add a single quote, then compare the response with the baseline: status code, length, wording, timing. A database error or a clear change suggests the input reaches a query.
Step 3 β€” Confirm with a safe checkSend a pair of harmless boolean conditions, one true and one false, and see if the page behaves differently. A short timing delay is an alternative for blind cases. Both only read behaviour and change nothing.
Step 4 β€” Stop at proofOne clear, repeatable difference is enough evidence. Do not extract data you do not need. Record the request, response and your reasoning.
⚠️ Watch out: Never use timing checks that stress a shared or real database. In a lab, keep delays to a few seconds and run them once.

Reviewers have an easier job. Search the codebase for queries built from strings. Look for concatenation or interpolation next to SELECT, INSERT, UPDATE or DELETE, and check ORM raw-query calls and dynamic SQL inside stored procedures, since OWASP notes both can still be injectable.

CODE REVIEW SEARCH
Run inside your own project folder
grep -rnE "(SELECT|INSERT|UPDATE|DELETE).*(\+|\$\{|%s|f\")" src/
grep -rnE "(raw|execute|query)\(.*(\+|\$\{|f\")" src/
src/auth.py:42: query = "SELECT * FROM users WHERE name='" + name + "'"

These patterns give leads, not verdicts. Read each hit and ask whether user input reaches it.

CISA bulletins in 2026 describe many flaws where user-controlled parameters were concatenated or interpolated into SQL without parameterisation, so these greps match what real advisories describe. Once you have a finding, judge how serious it is and whether it is real. The broken access control and IDOR guide shows the same evidence-first habit.

🧠 Quick check

You see a different response length after adding a single quote. What is the right next step?

Prevention: fix sql injection in the code

I want to show you the fix now, because understanding sql injection only pays off when you can close the hole. Everything here runs against your own machine or a deliberately vulnerable practice app. Never test a fix or a flaw on a system you do not have written permission to touch.

The main defence is simple to say. Define the SQL structure first, then pass the values separately so the database never mistakes them for syntax. OWASP calls this binding values through the database API [1], and the 2025 Top 10 also prefers a safe, parameterized interface [10].

🧭 Fix the vulnerable login query

Step 1 β€” Spot the concatenationFind the line that glues user input into the SQL string. This is the flaw we reproduced in the lab.
Step 2 β€” Write the structure with placeholdersUse ? markers. A marker can only stand for a data value, so the input stays data.
Step 3 β€” Bind the valuesPass username and password as parameters through the driver. The database now treats a quote as an ordinary character.
VULNERABLE VERSUS FIXED (PYTHON, SQLITE)
# Vulnerable: input becomes part of the SQL syntax
q = "SELECT * FROM users WHERE name='" + name + "' AND pw='" + pw + "'"
cur.execute(q)
# Fixed: structure and values are separate
cur.execute("SELECT * FROM users WHERE name = ? AND pw = ?", (name, pw))

Same query, but the second form sends the values to the database separately from the SQL text.

Notice what changed. The text of the query no longer depends on anything the user typed. That is the whole idea.

🚫 Common mistake: Do not try to escape quotes by hand. OWASP advises against it because escaping rules differ between SQL dialects and are easy to get wrong.

Stored procedures and ORMs are not magic. Binding protects the call, but dynamic SQL built by concatenation inside a procedure is still injectable. The same goes for ORMs such as Hibernate when you build queries from strings, so check raw query methods carefully.

Placeholders cannot stand for table names, column names or keywords like ASC and DESC. For a sort order, map the user's choice to a fixed value on the server.

ALLOW-LIST FOR SORTING
allowed = {"name": "name", "date": "created_at"}
col = allowed.get(sort, "name")
direction = "DESC" if order == "desc" else "ASC"
cur.execute(f"SELECT * FROM items ORDER BY {col} {direction}")

Only values from your own dictionary reach the query text, so user input never does.

β˜‘οΈ Defence in depth around the fix

🧠 Quick check

Which change actually removes the sql injection flaw in a login query?

I build a tiny local database so you can run the vulnerable and fixed queries yourself and see the difference.

LOCAL SQLITE DEMO
cat > demo.py <<'EOF'
import sqlite3
db = sqlite3.connect(':memory:')
db.execute('CREATE TABLE users (name TEXT, pw TEXT)')
db.execute("INSERT INTO users VALUES ('alice','secret')")
name, pw = "alice' –", 'wrong'
q = "SELECT * FROM users WHERE name='" + name + "' AND pw='" + pw + "'"
print('vulnerable:', db.execute(q).fetchall())
print('fixed:', db.execute('SELECT * FROM users WHERE name = ? AND pw = ?', (name, pw)).fetchall())
EOF
python3 demo.py
vulnerable: [('alice', 'secret')]
fixed: []

The concatenated query returns a row for a wrong password, while the parameterized query returns an empty list.


Retest the fix and keep learning

I want to close the loop now, because a finding is only finished when the fix is proven. We found the weakness in the lab, we looked at how parameter binding removes it, and now I will rerun the same test against the fixed version. Everything here runs only against the SecurityElites practice lab or your own localhost copy of a deliberately vulnerable app. Never repeat it on a system you do not own or have written permission to test.

The idea is simple. The same input that once changed the query logic should now be treated as a plain string, because the database receives the structure and the values separately. That is the whole point of defending against sql injection at the code level [1].

🧭 Retest the login against the fixed build

Step 1 β€” Confirm you are on the fixed versionCheck the lab or your local app shows the patched build. Note the URL, the date and the version in your notes so the evidence is traceable.
Step 2 β€” Replay the exact same testSend the same single quote and the same logic-changing input you used in the vulnerable run, in the same field, with the same proxy settings. Changing nothing else keeps the comparison honest.
Step 3 β€” Read the responseYou should see an ordinary failed login, the same message as for a wrong password. No database error, no changed behaviour, no session for the admin.
Step 4 β€” Check a normal login still worksLog in with a valid test account. A fix that breaks real users is not a fix.
RETEST NOTES
Vulnerable build, before the fix
Input treated as SQL syntax -> query logic changes -> unexpected login
Fixed build, after the fix
Input treated as a literal string -> no row matches -> Invalid username or password
Local copy: rerun the same check with python3 demo.py and expect fixed: []

What you should observe when the retest passes. The wording of the message depends on the lab.

🧠 Quick check

Why does the same input fail against the fixed build?
πŸ’‘ Tip: Hiding errors alone is not a pass. If the failed login looks calm but the query is still concatenated, a quiet behaviour difference can still give the flaw away.
πŸ§ͺ HANDS-ON LAB Β· BEGINNER Β· 25 MIN Β· SECURITYELITES LAB
SQL Injection β€” Login Bypass

Use this lab to practise the whole cycle: find the flaw, then write down what the fix must change and how you would prove it worked.

What to try
β–Έ Observe normal login behaviour first and record the responses.
β–Έ Probe the fields with a single quote and compare the response to a normal failure.
β–Έ Reason about how the server might be building its query from your input.
β–Έ Then describe, in your own words, the code change that would stop it.

What to notice: How the response changes when your input breaks the query shape What evidence you would need to put in a report

For next steps, start with the ethical hacking roadmap to see where injection sits in a full learning path. Then read the broken access control and IDOR guide, which pairs well with login flaws, and the server-side template injection guide to see the same data-versus-command mistake in another interpreter. The command injection explainer shows how it reaches the operating system.

Keep practising on the PortSwigger Web Security Academy, and write a short report for each lab: what you tested, what you saw, the impact and the fix. That habit is what turns lab practice into real bug bounty skill.

β˜‘οΈ Before you move on


Your Checklist

β˜‘οΈ SQL injection test and fix checklist

🚫 Mistakes I See Most Often

Trying to stop sql injection by escaping quotes or blocking certain characters by hand.Escaping rules differ between SQL dialects and are easy to get wrong. Use parameterized queries so the values are bound separately, and treat any manual escaping as a warning sign in code review.
Assuming stored procedures or an ORM make the code safe automatically.Search for dynamic SQL built by concatenation inside procedures and for raw-query calls in the ORM. Binding protects the call, but a string-built query inside it is still injectable.
Treating a hidden error message as proof the fix works.Rerun the original test and check the behaviour, not just the error. If the query is still concatenated, a quiet difference in the response can still leak information. Confirm in the code that values are bound.

What I Want You to Remember

SQL injection happens when untrusted data becomes part of a query's syntax, so the database cannot tell your data from the developer's commands.
The main fix is to separate structure from values: define the query first, then bind the values through the database API.
In-band, blind and out-of-band are sorted by how the answer reaches the tester: in the page, through true or false behaviour and timing, or through an external lookup.
Stored procedures, ORMs, escaping and WAFs are not complete fixes, because dynamic SQL built by string joining can still be injectable.
Parameters cannot stand for table names, column names or keywords, so use server-side allow-lists there, and give the application database account least privilege.
A finding is only finished when you retest the same input against the fixed code and see it treated as a plain string.

🧠 Check Your Understanding

What is the main fix for sql injection?
A page looks identical whether a test is true or false, so a tester adds a deliberate short delay to see the answer. Which type is this?
Why can a parameterized query not protect an ORDER BY column chosen by the user?

❓ Questions People Ask

What is sql injection and how does it work?
SQL injection happens when untrusted data becomes part of a query's SQL syntax. SQL mixes data and commands in one string, so crafted input can leave the data context and enter the command context. The database then runs what the attacker wrote as if the developer had written it.
How do I practice sql injection testing safely and legally?
Use intentionally vulnerable labs such as the SecurityElites SQL Injection login bypass lab, your own localhost setup, or the free PortSwigger Web Security Academy. Never probe a real site without written permission, even with good intentions. A separate browser profile and an intercepting proxy such as Burp Suite keep your testing tidy.
What is the best way to prevent sql injection?
Define the SQL structure separately from the data and bind the values through the database API, which is called parameterized queries. Add server-side allow-lists for parts parameters cannot cover, and give the application database account least privilege. These layers limit the damage if one fails.
Are parameterized queries and prepared statements enough to stop sql injection?
They stop injection in the values you bind, and they are the preferred defence. They do not help where you build table names, column names or keywords from user input, so use allow-lists there. They also do not protect dynamic SQL built by string joining elsewhere in the code.
Are stored procedures and ORMs safe from sql injection?
Not automatically. Binding arguments protects the call, but dynamic SQL built by concatenation inside a procedure is still injectable. ORMs such as Hibernate can be injectable too when you build queries from strings, so review raw-query calls closely.
What is the difference between in-band, blind and out-of-band sql injection?
In-band returns the answer in the page itself, through database errors or UNION results. Blind shows nothing directly, so the tester watches true or false changes or timing delays. Out-of-band makes the database trigger an external lookup or request when even timing is unreliable.
Is sql injection still a threat in 2026, and where does it rank in the OWASP Top 10?
Yes. In the OWASP Top 10:2025, injection is category A05:2025, down from third place in the previous edition, and SQL injection sits inside it. CISA's 2026 bulletins and its Known Exploited Vulnerabilities catalogue still list new SQL injection flaws, including ones in widely used products.
πŸš€ Where to go next: Read the ethical hacking roadmap to see where injection fits, then move on to the broken access control and IDOR guide, which pairs well with login flaws. Keep practising on the PortSwigger Web Security Academy and write a short report for each lab.

🧩 More in the Ethical Hacking and Bug Bounty series

πŸ“š Keep Learning on SecurityElites

Written by Mr Elite. Reviewed by Mr Elite, last reviewed on .

ME
Mr Elite
Owner, SecurityElites
I teach AI red teaming and ethical hacking through hands-on labs at SecurityElites.
⚡
Join free to earn XP for reading this article Track your progress, build streaks and compete on the leaderboard.
Join Free
Lokesh N. Singh aka Mr Elite
Lokesh N. Singh aka Mr Elite
Founder, Securityelites Β· AI Red Team Educator
Founder of Securityelites and creator of the SE-ARTCP credential. Working penetration tester focused on AI red team, prompt injection research, and LLM security education.
About Lokesh ->

Leave a Comment