PHP › PDO & Databases
How do you use named placeholders in a PDO prepared statement, and how do they improve readability compared to positional question mark placeholders?
IntermediateAnswer
Named placeholders let you use descriptive names, prefixed with a colon, within your SQL query instead of plain question marks, and when executing the statement, you provide an associative array mapping those exact placeholder names to their corresponding values, which is especially helpful for improving readability in queries with several parameters, since it becomes immediately clear which value corresponds to which specific part of the query without needing to carefully count question mark positions.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email AND status = :status');
$stmt->execute(['email' => $email, 'status' => 'active']);Real-world example A complex query filtering users by several different criteria uses named placeholders, making it immediately clear at a glance which specific value corresponds to which condition in the query, compared to a series of anonymous question marks that would require careful counting to interpret correctly.