
How to Prevent SQL Injection in PHP (MySQL + PDO)
Introduction
SQL injection is a common security issue in web applications. It happens when user input is added directly into a database query without proper handling. An attacker can change the query and access or modify data.
In this guide, you will learn how to prevent SQL injection in PHP using MySQL and PDO. You will also see a simple example of how SQL injection works and why it is dangerous.
If you are new to databases, you can first read our guide on connecting to MySQL in PHP for a better understanding of how queries work.
What is SQL Injection?
SQL injection is a technique where an attacker inserts malicious input into a query. This can change how the query behaves and allow unauthorized access to data.
If a developer directly uses user input inside a query, the database cannot distinguish between normal input and malicious commands. This can lead to data breaches, data loss, or even complete control over the database.
How It Happens (Example)
Let’s say you have a login form where users enter their username and password. The PHP code might look like this:
$email = $_POST['email'];
$query = "SELECT * FROM users WHERE email = '$email'";
This looks simple, but it creates a security risk. The input is treated as part of the SQL query.
Example of an SQL Injection Attack
If a user enters this value:
' OR '1'='1
The query becomes:
SELECT * FROM users WHERE email = '' OR '1'='1'
Since the condition is always true, the database returns all rows. This can bypass login checks or expose sensitive data stored in the database.
Fix: Use PDO Prepared Statements to Prevent SQL Injection
Prepared statements are the safest way to prevent SQL injection in PHP. They separate the SQL query from user input.
// Database connection using PDO
$pdo = new PDO("mysql:host=localhost;dbname=test", "root", "");
// User input from a form
$email = $_POST['email'];
// Using a prepared statement to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
In this example, the structure of the query is fixed. The value of $email is treated as data only, which prevents SQL injection.
Best Practices
- Always use prepared statements with PDO or MySQLi.
- Validate and sanitize user input such as email format.
- Never trust user input directly.
- Use limited database permissions.
- Do not display database errors to users
- Keep your database and software up to date.
Conclusion
SQL injection can cause serious damage to your application and database. The best way to prevent SQL injection in PHP is to use prepared statements with PDO and follow secure coding practices.
By handling user input properly, you can protect your application from common security threats.
Further Reading
PHP PDO prepared statements documentation (official PHP docs)