What is SQL Injection, and why are Prepared Statements (PDO/MySQLi) the standard way to prevent it?

Last updated 15 June 2026

SQL Injection is the injection of malicious SQL through unsanitized user input that alters a query's intended logic; prepared statements stop it by separating the query structure from the data so input can never be executed as code.

  • What it is: An attacker crafts input that breaks out of a string and adds clauses, enabling data theft, bypassed auth, or destructive commands like DROP TABLE.

  • Why prepared statements are the standard:

    • The query template is parsed first; bound parameters are then supplied as pure data, so structure can't change.

    • They work uniformly for all value types and remove the need for fragile manual escaping.

  • Named vs positional placeholders: PDO supports both :name and ? placeholders; pick one per query for clarity.

  • Defense in depth: Still validate input, use least-privilege DB accounts, and whitelist anything that can't be bound (column/table names).

[lang:php] $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id'); $stmt->execute(['id' => $userId]); $user = $stmt->fetch();

  • https://en.wikipedia.org/wiki/PHP
  • https://lemon.io/for-developers/php-developer-jobs/
  • https://lan-portal.uob.edu.ly/visit/BOOK/529X432U02/modern-php_new__features_and_good-practices.pdf
  • https://lan-portal.uob.edu.ly/upload/MD/D57953S372/modern-php__new_features_and__good__practices.pdf
  • https://news.ycombinator.com/item?id=30786927
  • https://kvnc-inc.medium.com/solid-principles-in-php-1c41069e9af6
  • https://www.shkodenko.com/
  • https://confoo.ca/en/2024/sessions
All PHP interview questions