PHP
Secure SQL Queries with PHP PDO Prepared Statements
Protect your web applications from SQL injection attacks by using PHP PDO prepared statements with parameterized queries for safe database interactions.
<?php
$dsn = 'mysql:host=localhost;dbname=mydb';
$username = 'user';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$userId = 123;
$status = 'active';
// Prepared statement to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id AND status = :status");
// Bind parameters
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->bindParam(':status', $status, PDO::PARAM_STR);
// Execute the statement
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
echo "User found: " . $user['username'];
} else {
echo "User not found.";
}
} catch (PDOException $e) {
die("Database error: " . $e->getMessage());
}
?>
How it works: This snippet demonstrates how to use PDO prepared statements in PHP to safely query a database. Instead of directly embedding user input into the SQL query, placeholders like `:id` and `:status` are used. Parameters are then bound to these placeholders, ensuring that the database engine treats input as data, not executable code, effectively preventing SQL injection attacks.