Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 36

SQL Injection Prevention in PHP

In this lesson: Stop SQL injection in PHP using PDO prepared statements — attack example, safe code and checklist for login forms. Secure now.

What is SQL injection

SQL injection is an attack where a user sneaks SQL code into an input — like a login box — and, if you build your query by pasting that input in, the database runs the attacker's code. It can read private data, change records, or even delete whole tables. It is one of the most serious web security risks.

⚠️ The one rule that prevents it: never build SQL by pasting user input. Use prepared statements.

How the attack works

Imagine a login that pastes the email straight into SQL. A normal user enters their email; an attacker enters:

' OR '1'='1

The query becomes ... WHERE email = '' OR '1'='1', which is always true — so the attacker logs in without a password. The danger is treating input as part of the SQL.

The dangerous way

<?php
  // NEVER do this:
  $email = $_POST["email"];
  $sql = "SELECT * FROM users WHERE email = '$email'";
  $result = $pdo->query($sql);
?>

Here the user's input becomes part of the SQL text. Any SQL they type runs. This single pattern is the cause of almost every injection attack.

The safe way: prepared statements

<?php
  $email = $_POST["email"];
  $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
  $stmt->execute([$email]);
  $user = $stmt->fetch();
?>
Query runs safely, input treated as data only

The ? is a placeholder. The real value goes in execute(), and the database treats it strictly as data — never as SQL. Even ' OR '1'='1 is just harmless text now.

Named placeholders

PDO also supports clearer named placeholders for longer queries.

<?php
  $stmt = $pdo->prepare(
      "SELECT * FROM users WHERE email = :email AND status = :status"
  );
  $stmt->execute([":email" => $email, ":status" => "active"]);
?>

Named placeholders like :email make it obvious which value goes where — helpful when a query has several inputs.

Extra good habits

  • Least privilege: give the database user only the permissions it needs.
  • Validate input: still check that data is the right shape (a valid email, a number, etc.).
  • Hide errors in production: do not show raw SQL errors to users; log them instead.
  • Escape output: when displaying data, use htmlspecialchars to also block XSS.

Common mistakes

  • Pasting input into SQL. The root cause — always use placeholders.
  • Skipping prepared statements for SELECT. Search boxes are a classic injection point too.
  • Relying only on escaping. It is easy to forget; prepared statements are safer.
  • Showing raw SQL errors. They reveal your structure to attackers.

Summary

  • SQL injection runs an attacker's SQL through unsafe input.
  • The cause is pasting user input directly into a query.
  • Prepared statements send SQL and values separately — the reliable fix.
  • Use placeholders (? or :name) for every user value, including SELECT.
  • Add validation, least privilege and hidden errors as extra layers.

Next, apply this in PHP MySQL connection, or block XSS with XSS prevention.

Frequently Asked Questions

What is SQL injection?
SQL injection is an attack where a user types SQL code into an input field, and if you paste that input straight into your query, the database runs the attacker's code. It can read, change or delete your data. It is one of the most common and dangerous web vulnerabilities.
How do prepared statements stop SQL injection?
A prepared statement sends the SQL structure and the values separately. The database treats the values purely as data, never as commands. So even if a user types SQL, it is stored as plain text and cannot run.
Is escaping input enough to prevent SQL injection?
Escaping helps but is error-prone and easy to forget. Prepared statements are the reliable, recommended defence. Use them for every query that includes any user-supplied value.
Which is better for security, PDO or MySQLi?
Both support prepared statements and both are secure when used correctly. PDO is often preferred for its clean, consistent API and named placeholders, but the key point is: always use prepared statements in whichever you choose.
Do I need prepared statements even for a SELECT?
Yes. Any query that includes user input — SELECT, INSERT, UPDATE or DELETE — can be attacked. A search box feeding a SELECT is a classic injection point, so use a prepared statement there too.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicREST API Your progress: 36 / 50 (72%) · Lesson 37 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free