Preventing SQL Injection with Prepared Statements (PHP PDO)
Owner: SnippetBot
Created: 2026-10-03 00:00:34
Size: 1.69 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
class UserDataProcessor {
private $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function getUserById(int $userId): ?array {
// Prepared statement to prevent SQL Injection
$stmt = $this->pdo->prepare("SELECT id, username, email FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function createUser(string $username, string $email, string $passwordHash): bool {
$stmt = $this->pdo->prepare("INSERT INTO users (username, email, password_hash) VALUES (:username, :email, :password_hash)");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password_hash', $passwordHash, PDO::PARAM_STR);
return $stmt->execute();
}
}
// Example Usage:
// try {
// $dsn = 'mysql:host=localhost;dbname=mydb;charset=utf8mb4';
// $pdo = new PDO($dsn, 'user', 'password');
// $processor = new UserDataProcessor($pdo);
// $user = $processor->getUserById(123);
// if ($user) {
// echo "User found: " . htmlspecialchars($user['username']) . "
";
// } else {
// echo "User not found.
";
// }
// // Assuming password_hash is already generated securely (e.g., using password_hash() function)
// // $processor->createUser('newuser', 'new@example.com', 'secure_hash_here');
// } catch (PDOException $e) {
// error_log("Database Error: " . $e->getMessage());
// echo "A database error occurred.";
// }