How to Prevent SQL Injection in PHP

 In today’s web-driven world, data breaches often begin with one overlooked flaw—SQL injection. It’s one of the most common attacks against PHP websites, and the worst part? It can happen with just a simple text input.

 

🚨 The Problem: A Tiny Input Field, a Massive Security Risk

Imagine you’re building a PHP login page. A user enters their email and password, and your code does something like this:

$email = $_POST['email'];

$password = $_POST['password'];

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

Seems harmless, right?

Now, a malicious user types this into the email field:

' OR 1=1 --

The resulting SQL becomes:

SELECT * FROM users WHERE email = '' OR 1=1 --' AND password = ''

The attacker bypasses your login completely—gaining access to any user account.

 

The Solution: Use Prepared Statements with PDO

Prepared statements prevent SQL injection by keeping the query and the data separate. No matter what a user inputs, it can’t alter your SQL logic.

Here’s how to do it the right way using PHP PDO:

$pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");

 

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND password = :password");

$stmt->execute([

  'email' => $_POST['email'],

  'password' => $_POST['password']

]);

With this approach, ' OR 1=1 -- is treated as a harmless string, not executable SQL.

 

πŸ” Why This Works

Prepared statements:

  • Separate SQL logic from input values, neutralizing harmful commands.
  • Prevent attackers from injecting code, even if the input looks like a valid query.
  • Automatically escape data, reducing developer error.

It’s like locking each door of your house individually—no master key (or malicious input) can open them all at once.

 

πŸ› ️ Real-Life Example

A freelance developer was hired to fix a bug in a small business website where users could search for customer records. The original code used raw SQL with user input.

After a strange spike in data leaks, it turned out that attackers were dumping customer records using SQL injection. Switching to PDO with prepared statements not only solved the issue instantly, but also helped the site pass security audits and regain trust.

 

πŸš€ Bottom Line

SQL injection is dangerous, but avoidable. Don’t rely on escaping strings or guessing what users might enter. Use prepared statements—it’s the safest, most professional way to handle SQL in PHP.

Comments

Popular posts from this blog

Top 5 AI Tools Every Developer Should Use to Boost Coding Efficiency

How To Generate Random Dates Between Two Date Range in SQL Server

Find the number of columns in a table