-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserController.php
More file actions
82 lines (73 loc) · 2.68 KB
/
UserController.php
File metadata and controls
82 lines (73 loc) · 2.68 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
class UserController {
private $pdo; // Database connection
// Constructor to initialize PDO
public function __construct($pdo) {
if (!$pdo) {
die("Error: Database connection not established.");
}
$this->pdo = $pdo;
}
// Fetch all users
public function getAllUsers() {
try {
$stmt = $this->pdo->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error fetching users: " . $e->getMessage());
}
}
// Get a single user by ID
public function getUserById($id) {
try {
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error fetching user: " . $e->getMessage());
}
}
// Create a new user
// Create a new user (UPDATED)
public function createUser($name, $email, $role, $status, $password) {
try {
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
$stmt = $this->pdo->prepare("INSERT INTO users (name, email, role, status, password) VALUES (?, ?, ?, ?, ?)");
return $stmt->execute([$name, $email, $role, $status, $hashedPassword]);
} catch (PDOException $e) {
die("Error creating user: " . $e->getMessage());
}
}
// Update user details
public function updateUser($id, $name, $email, $role, $status) {
$sql = "UPDATE users SET name = :name, email = :email, Role = :Role, Status = :Status WHERE id = :id";
$stmt = $this->pdo->prepare($sql);
$stmt->execute([
':name' => $name,
':email' => $email,
':Role' => $role, // 🔹 Capital "R" matches the column name
':Status' => $status, // 🔹 Capital "S" matches the column name
':id' => $id
]);
}
// Delete a user
public function deleteUser($id) {
try {
$stmt = $this->pdo->prepare("DELETE FROM users WHERE id = ?");
return $stmt->execute([$id]);
} catch (PDOException $e) {
die("Error deleting user: " . $e->getMessage());
}
}
// Reset user password
public function resetPassword($id, $newPassword) {
try {
$hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT);
$stmt = $this->pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
return $stmt->execute([$hashedPassword, $id]);
} catch (PDOException $e) {
die("Error resetting password: " . $e->getMessage());
}
}
}
?>