SQL injection is one of those web application vulnerabilities that has been known for decades, is relatively easy to prevent and yet is still successfully exploited today.
This article (updated in 2026) is about practical preventive security against SQL injection (aka SQLi). Some of the measures below directly prevent SQL injection. Others won't fix vulnerable code, but can significantly reduce the damage if a vulnerability somehow makes it into production.
Security is rarely about a single protection mechanism. The more layers you have, the harder it is for one mistake to become a serious incident.
What is SQL injection?
SQL injection happens when untrusted input becomes part of an SQL query and changes the intended meaning of that query.
Consider a very simple PHP example:
$email = $_GET<span>['email']</span>;
$sql = "SELECT * FROM users WHERE email = '$email'";
$result = $pdo->query($sql);
The developer expects $email to contain something like:
[email protected]
But the user controls this value.
An attacker may instead submit specially crafted input that changes the SQL statement itself.
This is the important part: data supplied by the user has accidentally become executable SQL syntax.
Depending on the query, database server, application architecture and privileges of the database user, SQL injection may allow an attacker to:
- bypass authentication;
- read data they should not have access to;
- modify data;
- delete data;
- expose personal or confidential information;
- execute database functions or stored procedures;
- and, in some configurations, potentially escalate the attack beyond the database.
SQL injection should not be confused with PHP code injection, JavaScript injection or OS command injection. They belong to the broader family of injection vulnerabilities, but they are different types of attacks.
According to the OWASP Top 10:2025, Injection remains one of the major web application security risks. SQL injection alone is associated with more than 14,000 CVEs in OWASP's dataset.
So yes, SQL injection is old.
Unfortunately, it is not dead.
Where can SQL injection happen?
Anywhere untrusted data can eventually reach an SQL query.
The obvious example is a form field:
Email: <span>[________________]</span>
But user-controlled data may also come from:
- URL query parameters;
- route parameters;
- HTTP headers;
- cookies;
- JSON API requests;
- uploaded files;
- webhook payloads;
- imported CSV files;
- values previously stored in the database.
The last case is worth remembering.
Just because data already exists in your database doesn't automatically make it trusted.
An attacker may submit malicious data today that gets stored without causing any problem. Another part of the application may later take this value and concatenate it into an SQL query.
This is sometimes called second-order SQL injection.
The basic rule should therefore be simple:
Treat data as data. Never allow it to become part of the SQL syntax.
Use prepared statements
This should be your first line of defense.
Do not build SQL queries by concatenating user-controlled values.
Bad:
$email = $_GET<span>['email']</span>;
$sql = "SELECT *
FROM users
WHERE email = '" . $email . "'";
$user = $pdo->query($sql)->fetch();
Better:
$stmt = $pdo->prepare(
'SELECT *
FROM users
WHERE email = :email'
);
$stmt->execute([
'email' => $_GET<span>['email']</span>,
]);
$user = $stmt->fetch();
With a prepared statement, the SQL query and its parameters are handled separately.
The database knows that:
SELECT *
FROM users
WHERE email = :email
is the SQL statement, while the value supplied for :email is data.
Even if the value contains quotes, spaces or SQL-looking characters, it remains a parameter instead of becoming part of the query structure.
PHP provides prepared statements through both PDO and MySQLi.
For example, using positional parameters with PDO:
$stmt = $pdo->prepare(
'SELECT *
FROM users
WHERE email = ? AND status = ?'
);
$stmt->execute(<span>[
$email,
'active',
]</span>);
Prepared statements should be the default whenever values are dynamically supplied to an SQL query.
Parameters cannot replace everything
There is one important limitation.
SQL parameters normally represent values, not SQL identifiers or SQL syntax.
For example, don't do this:
$sort = $_GET<span>['sort']</span>;
$sql = "SELECT *
FROM products
ORDER BY $sort";
You cannot simply replace the column name with a normal bound parameter:
ORDER BY :column
and expect it to work as an identifier.
If users are allowed to control something structural such as:
- a column used for sorting;
- sort direction;
- a table name;
- a report field;
use an explicit allow-list.
For example:
$allowedSortColumns = <span>[
'name',
'price',
'created_at',
]</span>;
$sort = $_GET<span>['sort']</span> ?? 'created_at';
if (!in_array($sort, $allowedSortColumns, true)) {
$sort = 'created_at';
}
$sql = "SELECT *
FROM products
ORDER BY $sort";
The user isn't allowed to provide arbitrary SQL anymore. They can only select one of the values defined by the application.
The same principle can be used for sort direction:
$direction = strtoupper($_GET<span>['direction']</span> ?? 'ASC');
if (!in_array($direction, <span>['ASC', 'DESC']</span>, true)) {
$direction = 'ASC';
}
Prepared statements plus allow-list validation cover the vast majority of normal application queries.
Input validation is important, but it is not SQL injection protection
User input should be validated.
If you expect an integer:
$userId = filter_input(
INPUT_GET,
'id',
FILTER_VALIDATE_INT
);
If you expect one of three possible values, validate against those three values.
If you expect a date, validate that it is actually a valid date.
But don't rely on validation alone to protect SQL queries.
And especially don't build your SQL injection protection around removing characters such as:
'
"
;
-
There are perfectly legitimate reasons for users to enter many of these characters.
Someone named:
O'Brien
should not break your application just because your security logic decided that an apostrophe looks suspicious.
Validate input because the application should know what data it accepts.
Use parameterized queries because the database must know the difference between data and SQL syntax.
Those are two separate responsibilities.
Review database user grants
Another good preventive measure is to review the privileges of the database account used by the web application.
This won't prevent SQL injection if your code is vulnerable.
But it can reduce the potential impact.
Your PHP application should definitely not connect to MySQL as:
root
Hopefully that doesn't need much explanation. :)
A typical application account may need privileges such as:
SELECT
INSERT
UPDATE
DELETE
on its own application database.
For example:
CREATE USER 'codedwell_app'@'10.%'
IDENTIFIED BY 'a-very-strong-password';
GRANT SELECT, INSERT, UPDATE, DELETE
ON codedwell.*
TO 'codedwell_app'@'10.%';
Compare this with:
GRANT ALL PRIVILEGES
ON *.*
TO 'codedwell_app'@'%';
There is rarely a good reason for a normal web request to require privileges such as:
CREATE
DROP
ALTER
FILE
CREATE USER
GRANT OPTION
Schema migrations may need some of these privileges, but your production web application usually doesn't.
This is where using different database identities can help.
For example:
Web application → SELECT, INSERT, UPDATE, DELETE
Reporting service → SELECT
Database migrations → CREATE, ALTER, DROP
Backup service → privileges required for backups
Don't give every component a master key just because it is convenient.
This is the classic principle of least privilege.
What about soft deletes?
In the original version of this article I suggested removing the DELETE privilege from the application and using soft deletes instead.
Soft deletes can still be a very useful application design pattern.
Instead of:
DELETE FROM users
WHERE id = 123;
you may do:
UPDATE users
SET deleted_at = NOW()
WHERE id = 123;
But this should not be treated as SQL injection protection.
An attacker who can inject an UPDATE query may still corrupt your data even if DELETE is unavailable.
Use soft deletes because they make sense for your application, audit requirements and data recovery strategy — not as a replacement for fixing SQL injection.
Use ORM and query builders — carefully
Modern frameworks such as Laravel, Symfony and others make SQL injection much harder to introduce accidentally.
For example, Laravel's query builder:
$user = DB::table('users')
->where('email', $email)
->first();
uses parameter binding behind the scenes.
Similarly, normal ORM operations with Doctrine, Eloquent and other mature libraries generally parameterize values for you.
This is one of the reasons using a mature framework is often safer than maintaining a large collection of homemade database functions.
However, using an ORM does not make your application immune to SQL injection.
Most frameworks allow developers to execute raw SQL.
For example, code conceptually similar to this remains dangerous:
$sql = "SELECT *
FROM users
WHERE email = '$email'";
DB::select($sql);
The fact that Laravel executes the query doesn't magically make the query safe.
The same applies to raw query expressions, custom repository methods and ORM query languages.
If you have to write raw SQL, use the framework's parameter binding mechanism.
A good rule is:
ORM for convenience. Parameterization for security.
Use code reviews
Code review is still one of the best tools for catching vulnerable code.
Yes - these days code reviews can be done using AI. But do not rely on AI only. If your team has at least two developers, cross-check important changes. An extra pair of eyes can catch:
- broken logic;
- missing authorization checks;
- unsafe SQL;
- forgotten validation;
- accidental logging of sensitive information;
- and plain old bugs.
And even senior developers should not hesitate to have junior developers review their code.
Senior developers make mistakes too.
Junior developers may also notice something simply because they approach the code from a different angle. At the same time, reviewing production code is one of the best ways for less experienced developers to learn.
Security should be part of normal code review, not something performed once a year before an audit.
Add automated security testing
Code review is useful, but modern development gives us more tools.
Security checks can be included directly in the CI/CD pipeline.
Depending on the project, consider:
- SAST — Static Application Security Testing;
- DAST — Dynamic Application Security Testing;
- dependency vulnerability scanning;
- secret scanning;
- automated security tests;
- fuzzing application inputs.
Static analysis can help detect suspicious query construction before code reaches production.
Dynamic scanners can test a running application for common vulnerabilities.
Neither replaces proper engineering, but both provide another opportunity to catch a mistake.
OWASP recommends combining source-code review with automated security testing rather than relying on only one technique.
Use a WAF
A Web Application Firewall (WAF) monitors HTTP traffic to your application and can detect or block suspicious requests.
Popular options include:
- Cloudflare WAF;
- ModSecurity;
- OWASP Core Rule Set (CRS);
- WAF services provided by cloud platforms.
A properly configured WAF may block many common SQL injection attempts before they reach your application.
That's useful.
But there is one important clarification compared with the original version of this article:
A WAF should never be considered a fix for SQL injection.
Attack payloads can be encoded, obfuscated or structured in unexpected ways. New bypass techniques also appear over time.
If your application contains:
$sql = "SELECT *
FROM users
WHERE id = " . $_GET<span>['id']</span>;
the correct solution is not to create another WAF rule.
Fix the query.
Think about WAF as another defensive layer:
Internet
↓
WAF
↓
Web application
↓
Parameterized queries
↓
Least-privileged DB user
↓
Database
An attacker should ideally have to get through several independent security controls.
Restrict database network access
Your database server normally should not be publicly accessible from the Internet.
If the application and database are inside the same private network, restrict MySQL connections to the hosts or network ranges that actually need access.
Instead of allowing:
'codedwell_app'@'%'
use a more restrictive host whenever your infrastructure allows it.
The network firewall should also restrict access to MySQL port 3306.
This does not prevent SQL injection through the application, but once again it reduces the attack surface.
Defense in depth.
Monitor what happens
Prevention is important.
Detection is important too.
Depending on the sensitivity and scale of your application, monitor things such as:
- unusual database errors;
- unexpected spikes in failed requests;
- WAF events;
- repeated suspicious query parameters;
- authentication anomalies;
- unusual database activity;
- unexpected exports or large queries.
Don't blindly log everything either.
Application logs themselves can become a security problem if they contain passwords, authentication tokens, complete payment information or other sensitive data.
The goal is to have enough information to investigate suspicious activity without creating a second database full of secrets.
Keep backups
Backups don't prevent SQL injection.
But sometimes preventive security also means preparing for the day when prevention fails.
If an attacker destroys or modifies data, a recent backup may be the difference between a bad afternoon and the end of your business.
Make sure backups are:
- automated;
- stored outside the production server;
- protected with separate credentials;
- encrypted where appropriate;
- retained according to your recovery requirements;
- and, most importantly, periodically tested.
An untested backup is only a theory.
SQL injection prevention checklist
Before deploying an application that talks to a SQL database, I would verify at least these points:
- SQL values are passed through prepared statements or parameter binding.
- User input is never directly concatenated into SQL queries.
- Dynamic identifiers use explicit allow-lists.
- Input is validated according to expected data types and values.
- The application does not connect as
rootor another administrative user. - The database account has only the privileges the application actually needs.
- Raw SQL and raw ORM expressions receive additional attention during code review.
- Static or dynamic security testing is part of the development process where practical.
- A WAF is used as an additional defensive layer where appropriate.
- The database is not unnecessarily exposed to the public Internet.
- Security and application events are monitored.
- Database backups exist and restore procedures have been tested.
None of these controls should be viewed in isolation.
Prepared statements are your primary protection against SQL injection. Least privilege limits potential damage. Code review and automated testing help catch mistakes. A WAF adds another barrier. Network restrictions reduce the attack surface. Monitoring helps you notice when something unusual happens. Backups help you recover when everything else goes wrong.
Security is a complex subject and there are many more aspects to consider when protecting a web application.
But SQL injection is one of those vulnerabilities where we already know very well how to prevent it.
There isn't much excuse for shipping it anymore. :)