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.
$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.
<?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"];
?>amy@example.comThe email value is safely bound to the :email placeholder, avoiding SQL injection risks.
<?php
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["Ben", "ben@example.com"]);
echo "User added";
?>User addedUsing ? 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.
