Skip to content
AgileLogics
Web Development

SQL Injection Explained: How It Works, Real-World Examples and Prevention Techniques

· By James Okafor · 14 min read
SQL Injection, Database Security, PHP, Laravel, Cybersecurity, Secure Coding, OWASP

Imagine visiting an online shopping website, entering your login details, and clicking the Sign In button. Everything looks normal, but behind the scenes, your application sends a database query to verify your credentials.

Now imagine that someone enters specially crafted input that changes how that database query works.

Instead of checking a legitimate username and password, the application accidentally executes a different SQL instruction.

This is the basic idea behind SQL Injection (SQLi), one of the most well-known web application security vulnerabilities.

SQL injection can allow attackers to access information they should not see, bypass authentication, modify database records, or even delete data, depending on the application's database permissions and configuration.

The good news is that SQL injection is largely preventable with established development practices.

In this guide, we'll explain SQL injection in simple language, explore practical examples, and show how developers can protect applications using PHP, Laravel, prepared statements, and secure database configuration.

What Is SQL Injection?

SQL Injection is a security vulnerability that occurs when an application includes untrusted user input in an SQL query without properly separating data from executable SQL instructions.

SQL stands for Structured Query Language. It is used to communicate with relational databases such as:

  • MySQL

  • PostgreSQL

  • Microsoft SQL Server

  • Oracle Database

  • MariaDB

Applications use SQL queries to retrieve, insert, update, and delete information.

For example, when a user logs into an application, the backend may execute a query similar to:

SELECT * FROM users
WHERE email = 'john@example.com';

The application expects the email address to be treated as data.

However, if user input is directly concatenated into the SQL query, an attacker may be able to change the meaning of the query.

This is what makes SQL injection dangerous.

In simple terms: SQL injection happens when an application mistakenly treats user-provided data as part of a database instruction.

How Does SQL Injection Work?

To understand SQL injection, let's consider a simple login functionality.

Imagine a PHP application that checks whether a user exists in the database.

A developer might write:

$email = $_POST['email'];
$password = $_POST['password'];

$sql = "SELECT * FROM users
        WHERE email = '$email'
        AND password = '$password'";

The application takes the submitted values and inserts them directly into the SQL query.

This is unsafe because the application does not distinguish between user data and SQL syntax.

An attacker may submit specially crafted input that changes the structure of the query.

For example, a classic SQL injection demonstration uses an input resembling:

' OR '1'='1' --

If this input is inserted unsafely into a SQL query, it may change the condition being evaluated.

The important point is that the database is no longer evaluating only the developer's intended query.

It is processing a query whose structure has been influenced by untrusted input.

This example is intentionally simplified. Actual behavior depends on the database engine, query structure, SQL dialect, and application configuration.

Why Is SQL Injection Dangerous?

SQL injection is not limited to login forms.

Any application that builds database queries using unsafe user input may be vulnerable.

Consider an eCommerce application that stores:

  • Customer information.

  • Email addresses.

  • Shipping addresses.

  • Order history.

  • Product information.

  • Payment transaction references.

  • Loyalty information.

A successful SQL injection attack may expose or modify some of this information.

The possible consequences include:

1. Unauthorized data access

Attackers may retrieve customer records, business information, or other sensitive database content.

2. Authentication bypass

Poorly implemented login queries may allow attackers to interfere with authentication checks.

3. Data modification

Attackers may alter existing database records if the vulnerable database account has sufficient permissions.

4. Data deletion

In some circumstances, attackers may execute destructive database operations.

5. Business disruption

Database manipulation or data loss can affect application functionality and business operations.

6. Regulatory and reputational consequences

Exposure of personal information may trigger legal, regulatory, contractual, and customer-trust consequences.

The actual impact depends on the vulnerability, database privileges, network access, and other security controls.

Common Types of SQL Injection Attacks

SQL injection can occur in different forms. Understanding these types helps developers identify vulnerabilities and build appropriate defenses.

1. In-Band SQL Injection

In-band SQL injection occurs when an attacker can use the same communication channel to influence a database query and observe the resulting information.

Two commonly discussed forms are:

Error-based SQL Injection

This occurs when database error messages reveal information about the database structure or query execution.

For example, poorly configured applications may expose detailed SQL errors directly to users.

UNION-based SQL Injection

This technique abuses SQL UNION operations to combine results from different queries when the vulnerable query structure permits it.

It can potentially expose information from other database records.

Developers should never expose raw database errors to API consumers.

2. Blind SQL Injection

Blind SQL injection occurs when an application does not directly display database query results or useful database error messages.

Instead, attackers attempt to infer information from indirect application behavior.

Two common forms include:

Boolean-based Blind SQL Injection

The attacker observes differences in application responses when a database condition evaluates to true or false.

Time-based Blind SQL Injection

The attacker observes whether the application response is delayed under particular database conditions.

Blind SQL injection can be difficult to detect because the application may appear to behave normally.

3. Second-Order SQL Injection

Second-order SQL injection occurs when malicious input is stored in the database and later used unsafely in another SQL query.

For example:

  1. An application accepts user-provided profile information.

  2. The information is stored in the database.

  3. Another part of the application retrieves that information.

  4. The retrieved value is inserted into a new SQL query without proper parameterization.

This is an important reminder that data does not become trustworthy simply because it has already been stored in your database.

Always use safe query construction, including when processing previously stored values.

Real-World Example: Vulnerable SQL Query in PHP

Let's look at a practical example.

Imagine an application that allows users to search for products by name.

A developer writes:

$productName = $_GET['product'];

$sql = "SELECT * FROM products
        WHERE name LIKE '%$productName%'";

$result = $pdo->query($sql);

At first glance, this may look straightforward.

However, the query directly includes user-controlled input.

An attacker may submit specially crafted input to alter the SQL statement.

The application should not build SQL queries by concatenating untrusted values.

The Correct Approach: Use Prepared Statements

A safer implementation uses PDO prepared statements:

$productName = $_GET['product'];

$sql = "SELECT * FROM products
        WHERE name LIKE :product";

$stmt = $pdo->prepare($sql);

$stmt->execute([
    'product' => '%' . $productName . '%'
]);

$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

Here is what changes:

  • The SQL query structure is defined separately.

  • User input is passed as a parameter.

  • The database driver handles parameter binding.

  • The input is treated as data rather than executable SQL syntax.

This is one of the most effective ways to prevent SQL injection.

How to Prevent SQL Injection in PHP

PHP developers commonly work with MySQL and PostgreSQL databases.

Regardless of the database, the principle remains the same: never construct SQL statements by directly concatenating untrusted input.

Here are some practical recommendations.

1. Use PDO Prepared Statements

PDO supports parameterized queries.

Example:

$stmt = $pdo->prepare(
    "SELECT id, name, email
     FROM users
     WHERE email = :email"
);

$stmt->execute([
    'email' => $email
]);

$user = $stmt->fetch(PDO::FETCH_ASSOC);

This separates query structure from input values.

2. Use MySQLi Prepared Statements

If your application uses MySQLi, you can also use prepared statements.

$stmt = $mysqli->prepare(
    "SELECT id, name, email
     FROM users
     WHERE email = ?"
);

$stmt->bind_param("s", $email);

$stmt->execute();

$result = $stmt->get_result();

Both PDO and MySQLi provide secure parameter-binding mechanisms when used correctly.

3. Validate Input Data

Validation helps ensure that incoming data follows the expected format.

For example, if an API expects a numeric product ID:

$productId = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if ($productId === false || $productId === null) {
    http_response_code(400);
    exit('Invalid product ID');
}

Validation is useful, but it should complement prepared statements rather than replace them.

4. Avoid Dynamic SQL Without Allowlisting

Sometimes applications need dynamic sorting.

For example:

GET /api/products?sort=price

SQL parameters cannot generally be used for table names, column names, or SQL keywords.

Therefore, use a strict allowlist:

$allowedSortColumns = [
    'name' => 'name',
    'price' => 'price',
    'created' => 'created_at'
];

$sort = $_GET['sort'] ?? 'name';

$sortColumn = $allowedSortColumns[$sort]
    ?? 'name';

$sql = "SELECT * FROM products
        ORDER BY $sortColumn ASC";

The SQL identifier comes from a predefined list, not directly from user input.

This approach is important whenever SQL structure must be dynamic.

How to Prevent SQL Injection in Laravel

Laravel provides several features that make secure database access easier.

However, developers must still understand how those features work and avoid unsafe query construction.

1. Use Laravel Query Builder

Laravel Query Builder uses parameter binding for values.

Example:

$users = DB::table('users')
    ->where('email', $email)
    ->get();

The framework handles the binding of the email value.

You do not need to manually escape the input before passing it to the query builder.

2. Use Eloquent ORM

Eloquent provides another convenient way to interact with database records.

$user = User::where(
    'email',
    $email
)->first();

This is preferable to constructing SQL statements through string concatenation.

3. Be Careful With Raw Queries

Laravel supports raw SQL through methods such as DB::raw() and whereRaw().

These methods are useful for complex queries, but they require additional care.

Unsafe example:

$users = DB::select(
    "SELECT * FROM users
     WHERE email = '$email'"
);

Safer example:

$users = DB::select(
    "SELECT * FROM users
     WHERE email = ?",
    [$email]
);

Always use parameter binding for untrusted values.

4. Validate Incoming Requests

Laravel provides convenient request validation.

$request->validate([
    'email' => [
        'required',
        'email'
    ],
    'password' => [
        'required',
        'string',
        'min:8'
    ]
]);

This ensures that incoming data follows the expected rules.

However, validation alone does not prevent SQL injection. Continue using parameterized database queries.

10 Best Practices to Prevent SQL Injection

Prepared statements are essential, but secure database development requires more than one technique.

Here are ten practices worth following.

1. Always Use Parameterized Queries

Keep SQL instructions separate from user-provided values.

Avoid building queries through string concatenation.

2. Validate All Incoming Data

Validate data types, formats, lengths, and expected values before processing requests.

3. Avoid Unnecessary Dynamic SQL

Use predefined allowlists for dynamic column names, sorting, and other SQL identifiers.

4. Apply Least-Privilege Database Permissions

Your application database account should have only the permissions it needs.

For example, an application that only reads product information should not require permission to drop database tables.

Where practical, use separate database accounts for different application responsibilities.

5. Do Not Expose Database Errors

Return safe error messages to users.

Log detailed diagnostic information securely on the server.

6. Keep Frameworks and Dependencies Updated

Use supported framework versions and apply security updates.

Outdated database drivers and application dependencies may introduce additional security risks.

7. Review Raw SQL Queries

Pay special attention to raw SQL, dynamic query construction, reporting queries, and administrative functionality.

8. Use Secure Database Configuration

Protect database credentials and restrict database network access.

Avoid exposing database services directly to the public internet unless there is a specific, properly secured requirement.

9. Perform Regular Security Testing

Review application code, run automated security checks, and test database-related functionality.

10. Monitor Suspicious Activity

Monitor unusual database access patterns, repeated errors, unexpected query behavior, and suspicious application requests.

Logging and monitoring can help identify potential attacks and investigate security incidents.

Common SQL Injection Prevention Mistakes

Even experienced developers can introduce SQL injection vulnerabilities when working with complex applications.

Here are some common mistakes to avoid.

Mistake 1: Assuming input validation is enough

Validating an email address or numeric ID does not automatically make a concatenated SQL query safe.

Use prepared statements.

Mistake 2: Relying on escaping alone

Manual escaping is easy to implement incorrectly and can depend on database-specific behavior and character encoding.

Prefer parameterized queries.

Mistake 3: Assuming an ORM makes everything safe

ORMs provide useful protections for normal query-building operations, but unsafe raw SQL can still introduce vulnerabilities.

Mistake 4: Trusting data stored in the database

Previously stored data may still contain untrusted values.

Use parameterized queries whenever that data is used in another SQL statement.

Mistake 5: Giving the application database administrator privileges

Excessive database permissions increase the potential damage from a compromised application.

Apply the principle of least privilege.

Mistake 6: Ignoring administrative endpoints

Search, reporting, export, and admin functionality can also introduce SQL injection vulnerabilities.

Review the entire application, not only public-facing forms.

How to Test an Application for SQL Injection

Security testing should be performed only on applications you own or have explicit permission to assess.

Developers can use several approaches to identify SQL injection vulnerabilities.

1. Manual Code Review

Review database queries and look for patterns such as:

  • SQL strings built through concatenation.

  • User-controlled values inserted into raw SQL.

  • Dynamic table or column names without allowlisting.

  • Unsafe reporting and search queries.

  • Unparameterized database operations.

2. Automated Security Testing

Several tools can help identify potential SQL injection issues.

OWASP ZAP

An open-source web application security testing tool.

Burp Suite

A security testing platform that helps inspect and assess web application requests.

SQLMap

A specialized open-source tool for detecting and testing SQL injection vulnerabilities in authorized environments.

Static Analysis Tools

Tools such as Semgrep can help identify unsafe query construction patterns in source code.

3. Review Application Logs

Look for unexpected database errors, unusual request patterns, and repeated failures.

Do not rely on logs alone, as successful exploitation may not always generate obvious database errors.

4. Test Both Positive and Negative Scenarios

Verify that legitimate requests work correctly and unexpected inputs are rejected or safely handled.

Test authentication, search, filters, sorting, reporting, and other database-backed features.

SQL Injection Security Checklist

Before releasing an application, review this checklist.

Database Queries

  • Use prepared statements.

  • Avoid direct SQL string concatenation.

  • Parameterize raw SQL queries.

  • Allowlist dynamic SQL identifiers.

  • Review complex database operations.

Application Security

  • Validate all incoming data.

  • Avoid exposing database errors.

  • Keep frameworks and database drivers updated.

  • Review authentication and authorization.

  • Secure administrative endpoints.

Database Configuration

  • Apply least-privilege permissions.

  • Protect database credentials.

  • Restrict database network access.

  • Maintain secure backups.

  • Monitor database activity.

Testing and Monitoring

  • Perform regular code reviews.

  • Use static analysis.

  • Conduct authorized security testing.

  • Monitor suspicious application behavior.

  • Review security findings before production releases.

Frequently Asked Questions (FAQs)

1. What is SQL injection in simple terms?

SQL injection is a security vulnerability that occurs when an application allows user input to change the structure or meaning of a database query.

2. Is SQL injection still a problem?

Yes. SQL injection remains an important web application security risk, particularly in applications that construct SQL queries using untrusted input.

3. What is the best way to prevent SQL injection?

The most important prevention technique is using parameterized queries or prepared statements. These keep SQL instructions separate from user-provided data.

4. Can Laravel prevent SQL injection?

Laravel's Query Builder and Eloquent ORM use parameter binding for normal query operations, helping protect against SQL injection. However, developers must still handle raw SQL and dynamic query construction carefully.

5. Does input validation prevent SQL injection?

Input validation helps reject unexpected or invalid data, but it is not a replacement for prepared statements. Both practices should be used together.

6. What is the difference between SQL injection and XSS?

SQL injection targets database queries by manipulating SQL instructions. Cross-Site Scripting (XSS) targets users' browsers by injecting malicious client-side content, typically JavaScript.

7. Can prepared statements completely prevent SQL injection?

Prepared statements provide strong protection when used correctly for query values. However, they do not automatically secure dynamically constructed SQL identifiers, unsafe query fragments, or every other database operation.

8. What is the OWASP SQL injection recommendation?

OWASP recommends using prepared statements with parameterized queries as the primary defense. It also recommends safe stored procedures, allowlist validation where necessary, and other defense-in-depth measures.

Final Thoughts

SQL injection is a well-understood security vulnerability, but it continues to affect applications when developers use unsafe database query practices.

The good news is that preventing it does not require complicated security architecture.

Start by separating SQL instructions from user input through prepared statements. Use your framework's secure query-building features, validate incoming data, apply least-privilege database permissions, and review raw SQL carefully.

If you are working with PHP or Laravel, make prepared statements, Query Builder, and Eloquent your default choices for database operations.

Most importantly, remember that every input reaching your application should be treated as untrusted, regardless of whether it comes from a website form, mobile application, API integration, or internal service.

Secure database queries are not just a coding preference. They are a fundamental part of protecting application data and user trust.

Keep learning, keep building, and make development more secure with AgileLogics.

Written by

James Okafor

DevOps engineer covering containers, CI/CD, and infrastructure workflows.

Share