What is SQL Injection in PHP?

SQL injection is an attack that attempts to inject SQL in input data, which is ultimately run against your application database. A structured query language (SQL) attack is not unique to PHP, any application which uses a database and accepts input is vulnerable to this type of attack. The objective of an SQL injection attack can be to:

  • Read sensitive data from the database
  • Update or even delete data stored in the database
  • Run administrative commands against the database

SQL Injection Examples

Our first injection example is a login form which passes an email and password to our application. We run a query to select the user, given the email.

Our code above uses the PDO class to query the database, we expect the running query to be something similar to:
The query is dynamically constructed with input supplied by the user, the email address: me@mail.com. But our query will only behave as we expect if the email address supplied does not contain a single quote character. An attacker can attempt an SQL injection attack by submitting an email like:
The resulting injection would then become:
Which is logically equivalent to:

Our second injection example is a comment form which submits a comment to our application. We run a query to update the comments for a blog post, given the comment.

We expect the update query to be something similar to:
An attacker can attempt an injection attack by submitting a comment like:
The resulting attack would then become:
The above query would update our comments but then DELETE all users. Many databases allow multiple queries separated by a semi-colon. The injection of a ; causes the update to run both queries. The double hyphen -- marks the rest of the query as a comment, which does not execute.

Preventing SQL Injection

There are various ways to prevent SQL injection, some of them are:

  • Input validation
  • Using a deny list together with a white list
  • Using stored procedures
  • Manually escaping characters
  • Using parameterized SQL statements

Parameterized queries require less maintenance and offers more security, let's update our code to use parameterized SQL statements.

We've updated our example SQL to use placeholders and the prepare statement. We also filter our input using filter_input before passing the user supplied value to our query.

Key Takeaways

  • SQL (or Structured Query Language) injection is a form of attack that aims to inject malicious SQL as input into our application
  • Injection can be from any input we receive and the form of SQL used in the attack can be varied
  • Prepared statements and input filtering can be used to prevent injection

Further Reading

This article is part of a security series on PHP, related articles: PHP XSS