PHP
Prevent SQL Injection Using PHP PDO Prepared Statements
Protect your PHP applications from SQL injection vulnerabilities by using PDO prepared statements to safely execute database queries with user input.
<?php
// NOTE: Ensure a database named 'testdb' exists and has a 'users' table with 'id', 'name', 'email' columns.
// Example table creation (MySQL):
// CREATE DATABASE testdb;
// USE testdb;
// CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255) UNIQUE);
// Database connection details
$dsn = 'mysql:host=localhost;dbname=testdb;charset=utf8mb4';
$user = 'username'; // Replace with your database username
$password = 'password'; // Replace with your database password
try {
// Establish PDO connection
$pdo = new PDO($dsn, $user, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false, // CRUCIAL for security: ensures real prepared statements
]);
echo "Database connected successfully.
";
// --- Example 1: INSERT data securely ---
$name = "John Doe";
$email = "[email protected]";
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name); // Bind parameter safely
$stmt->bindParam(':email', $email);
$stmt->execute();
echo "User '{$name}' inserted securely.
";
// --- Example 2: SELECT data securely ---
$search_name = "John Doe"; // This could be user provided input
$stmt = $pdo->prepare("SELECT id, name, email FROM users WHERE name = :name");
$stmt->bindParam(':name', $search_name); // Bind parameter safely
$stmt->execute();
echo "
Found users:
";
while ($row = $stmt->fetch()) {
echo "ID: {$row['id']}, Name: {$row['name']}, Email: {$row['email']}
";
}
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
?>
How it works: This PHP snippet demonstrates the critical security practice of using PDO prepared statements to prevent SQL injection attacks. Instead of concatenating user input directly into SQL queries, prepared statements separate the SQL logic from the data. The database first parses the query structure, then separately binds the user-provided values. This ensures that malicious input (like `'; DROP TABLE users; --`) is treated purely as data and not as executable SQL code, thus protecting your database from unauthorized access, modification, or deletion.