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

948 views

7

<?php
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Set up a tiny demo schema.
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)');

// Insert with named placeholders. Bind values, then execute.
$insert = $pdo->prepare('INSERT INTO users (name, email) VALUES (:name, :email)');
$insert->execute([':name' => 'Ada',   ':email' => '[email protected]']);
$insert->execute([':name' => 'Linus', ':email' => '[email protected]']);

// Read back with fetchAll.
$rows = $pdo->query('SELECT id, name, email FROM users ORDER BY id')->fetchAll(PDO::FETCH_ASSOC);
print_r($rows);

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.