Prepared Statements with PDO
User input should never be concatenated directly into SQL strings. Prepared statements allow you to bind parameters separately from the SQL text, preventing injection attacks and improving performance through statement reuse.
Creating a PDO connection
First, instantiate a PDO object using a DSN and credentials:
<?php
declare(strict_types=1);
$dsn = 'mysql:host=localhost;dbname=project;charset=utf8mb4';
$pdo = new PDO($dsn, 'dbuser', 'secret', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
?>
Binding parameters
Prepare the statement with placeholders, then bind values using bindValue() or pass them to execute():
<?php
declare(strict_types=1);
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->bindValue(':email', $userEmail, PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
?>
When inserting or updating rows, binding prevents type juggling and quoting errors. The database driver handles all escaping.