Overview
PDO prepared statements separate SQL structure from parameter values. They are a key defense against SQL injection when used correctly.
Basic pattern
$stmt = $pdo->prepare(
'SELECT id, email FROM users WHERE email = :email'
);
$stmt->execute([
'email' => $email,
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Important rules
- Bind user-supplied values instead of concatenating them into SQL.
- Placeholders represent values, not table names, column names or SQL keywords.
- Use an allow-list when a column or sort direction must be dynamic.
- Do not reuse named placeholders in ways unsupported by the configured PDO driver and prepare mode.
- Choose an explicit error mode and handle exceptions safely.
Insert example
$stmt = $pdo->prepare(
'INSERT INTO feedback (message) VALUES (:message)'
);
$stmt->execute(['message' => $message]);
Official resource
PDO prepared statements: https://www.php.net/manual/en/pdo.prepared-statements.php