Intermediate LevelPHP 8+
How does PDO (PHP Data Objects) prevent SQL Injection using Prepared Statements?
❓ Interview Prompt: Explain database abstraction with PDO, binding parameters, and why prepared statements defeat SQL injection.
PDO (PHP Data Objects) is a lightweight interface for accessing databases in PHP, supporting 12+ database drivers with a unified API.
How Prepared Statements Defeat SQLi:
When using PDO Prepared Statements ('$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email")'), execution happens in two distinct steps:
1
Prepare: PHP sends the SQL template with placeholders (':email') to the database. The database compiles the query structure before seeing any user data.
2
Execute: User parameters are sent separately as literal data strings. Because the SQL structure is already compiled, user input cannot alter query logic or execute injected SQL commands.
Code Implementation Example
php
<?php
declare(strict_types=1);
$dsn = "mysql:host=localhost;dbname=shop;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false, // Native prepared statements!
];
$pdo = new PDO($dsn, "user", "pass", $options);
// Prepared Statement with Bound Parameters
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE email = :email AND status = :status");
$stmt->execute([
':email' => $_GET['email'], // Safely bound literal string!
':status' => 'active'
]);
$user = $stmt->fetch();💡Securing database queries against SQL injection using PDO prepared statements.
🎯 Interview Key Takeaway
Always use PDO prepared statements with parameter binding (:placeholder) and set ATTR_EMULATE_PREPARES to false to eliminate SQL injection.
#PDO#SQL Injection#Security#Intermediate
Back to all PHP 8+ Questions→