PHP Snippet

PHP PDO Prepared Statements

Difficulty: Medium

Prepared statements protect you from SQL injection by separating the query template from the data. This snippet shows the canonical PDO pattern: connect, `prepare`, bind parameters by name, `execute`, and fetch. The runnable accordions use an in-memory SQLite database (`sqlite::memory:`) so the test wrapper does not need an external DB; the same code shape works against MySQL or PostgreSQL by changing the DSN.

Code Snippets
/

PHP PDO Prepared Statements

PHP PDO Prepared Statements

Prepared statements protect you from SQL injection by separating the query template from the data. This snippet shows the canonical PDO pattern: connect, `prepare`, bind parameters by name, `execute`, and fetch. The runnable accordions use an in-memory SQLite database (`sqlite::memory:`) so the test wrapper does not need an external DB; the same code shape works against MySQL or PostgreSQL by changing the DSN.

PHP
Medium
3 snippets
php-pdo
sql
security
encapsulation

947 views

7

PDO is PHP's database-agnostic interface; the DSN string (sqlite::memory: here) tells it which driver to use. Setting ERRMODE_EXCEPTION is essential: without it, PDO silently swallows query errors and you have to check return values everywhere. prepare parses and validates the SQL once; execute runs it with new parameter values, which means repeated inserts share the parsed plan. Named placeholders (:name, :email) are easier to read than positional ? and impervious to argument-order mistakes.