PHP ยท Chapter 43 of 44

PHP Prepared Statements & Security

Prepared statements separate SQL code from data, preventing user input from being interpreted as part of the SQL command. This is the primary defense against SQL injection, one of the most common and dangerous web security vulnerabilities.

With PDO, you write a query with placeholders (either ? or named parameters like :name), then bind actual values to those placeholders before executing, ensuring input is always treated as data, never as executable SQL.

Syntax
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute([":id" => $id]);

Using placeholders

prepare("SELECT * FROM users WHERE email = :email") defines a query with a named placeholder, which is later filled in safely using execute([":email" => $email]).

Why prepared statements matter

Without prepared statements, malicious input like ' OR '1'='1 could alter the meaning of a SQL query. Prepared statements ensure the database always treats input strictly as data.

Example 1 (php)
<?php
  $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
  $stmt->execute([":email" => "amy@example.com"]);
  $user = $stmt->fetch(PDO::FETCH_ASSOC);
  echo $user["email"];
?>
Output
amy@example.com

The email value is safely bound to the :email placeholder, avoiding SQL injection risks.

Example 2 (php)
<?php
  $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
  $stmt->execute(["Ben", "ben@example.com"]);
  echo "User added";
?>
Output
User added

Using ? placeholders with an ordered array of values is another valid way to bind input safely.

Key points

  • Prepared statements separate SQL structure from user-supplied data.
  • Placeholders can be positional (?) or named (:name).
  • execute() safely binds actual values to the placeholders.
  • Prepared statements are the main defense against SQL injection attacks.
๐Ÿ’ก Note: Always use prepared statements for any query involving user input โ€” never build SQL by concatenating raw strings.

๐Ÿ“ Quick Quiz

1. What is the main security benefit of prepared statements?

2. Which method binds actual values to a prepared statement's placeholders?

3. What are the two placeholder styles supported by PDO?