Back to results for “Security”
PHP › PDO & Databases

What is a prepared statement in PDO, and why is using one considered essential for writing secure database queries?

Beginner

Answer

A prepared statement separates a SQL query's structure from the actual data values being used within it, first sending the query template to the database with placeholders for any variable data, and then separately sending the actual values to be safely substituted into those placeholders, which prevents SQL injection attacks entirely since the database always treats the substituted values as pure data rather than as part of the executable SQL command itself.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();
Real-world example A login form uses a prepared statement to safely check a submitted email address against the database, completely preventing a malicious user from being able to manipulate the query's structure through carefully crafted input, unlike directly concatenating user input into a raw SQL string.

Common follow-ups: What is the difference between positional placeholders and named placeholders in a prepared statement?;Why does using string concatenation to build a SQL query create a serious security vulnerability?