PHP
Prevent SQL Injection with Prepared Statements
Implement secure database interactions in PHP using PDO's prepared statements to prevent SQL injection vulnerabilities, protecting your application's data integrity.
<?php
// Database connection (replace with your actual credentials)
$host = 'localhost';
$db = 'your_database';
$user = 'your_user';
$pass = 'your_password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// Unsafe example (DO NOT USE):
// $username = $_POST['username'];
// $password = $_POST['password'];
// $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
// $stmt = $pdo->query($sql);
// Secure example using prepared statements:
$username = $_POST['username'] ?? ''; // Sanitize input as needed
$password = $_POST['password'] ?? '';
$sql = "SELECT id, username FROM users WHERE username = :username AND password = :password";
$stmt = $pdo->prepare($sql);
// Bind parameters securely
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR); // Note: Passwords should be hashed!
$stmt->execute();
$user = $stmt->fetch();
if ($user) {
echo "Login successful for user: " . $user['username'];
} else {
echo "Invalid credentials.";
}
?>
How it works: This PHP snippet demonstrates how to prevent SQL injection attacks using PDO (PHP Data Objects) prepared statements. Instead of concatenating user input directly into the SQL query, prepared statements send the query structure and user data separately. The database engine then combines them, ensuring that user input is treated as data, not as executable code. This example uses named placeholders (`:username`, `:password`) and `bindParam` to explicitly define the type of each parameter, further enhancing security.