PHP
Preventing SQL Injection with Prepared Statements in PHP
Secure PHP web applications by using PDO prepared statements. Learn to prevent SQL injection vulnerabilities, safeguarding your database from malicious queries and potential data breaches.
<?php
// Database connection (replace with your actual credentials)
$dsn = 'mysql:host=localhost;dbname=your_database;charset=utf8mb4';
$username = 'your_username';
$password = 'your_password';
try {
$pdo = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false, // Ensure real prepared statements
]);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// --- Example 1: SELECT statement ---
$userId = $_GET['id'] ?? null; // User input, potentially malicious
if ($userId !== null) {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();
if ($user) {
// echo "User found: " . htmlspecialchars($user['username']);
} else {
// echo "User not found.";
}
}
// --- Example 2: INSERT statement ---
$username = $_POST['username'] ?? 'guest';
$email = $_POST['email'] ?? '[email protected]';
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
if ($stmt->execute()) {
// echo "New user created successfully!";
} else {
// echo "Error creating user.";
}
?>
How it works: SQL Injection is a critical web security vulnerability that allows attackers to interfere with queries. This snippet demonstrates how to use PHP Data Objects (PDO) with prepared statements to prevent SQL Injection. By separating the SQL query structure from the user-supplied data, PDO ensures that input values are treated as data, not as executable code, effectively neutralizing injection attempts.