Select Git revision
Forked from
IF3110-2023-01-18 / Tugas Besar 1
Source project has a limited visibility.
User.php 2.65 KiB
<?php
// app/models/User.php
require_once(__DIR__ . '/../../db/connect.php');
class UserModel {
public function createUser($name, $username, $email, $hashedPass, $isAdmin) {
global $db;
$response = [
'success'=> true,
'message'=> ''
];
try {
$stmt = $db->prepare("INSERT INTO users (user_name, username, user_email, user_hashedPass, isAdmin) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$name, $username, $email, $hashedPass, $isAdmin]);
$response['message'] = "User created successfully";
return $response;
} catch (PDOException $e) {
$response['success'] = false;
// Check if the error code corresponds to a unique constraint violation.
if ($e->getCode() === '23000') {
// Handle the error as a duplicate entry.
$response['message'] = "Username or email already exists. Please choose a different one.";
return $response;
} else {
// Handle other database errors.
$response['message'] = "Database error: " . $e->getMessage();
return $response;
}
}
}
public function getUser($userId) {
global $db;
$stmt = $db->prepare("SELECT * FROM users WHERE user_ID = ?");
$stmt->execute([$userId]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function getUserByEmail($email) {
global $db;
$stmt = $db->prepare("SELECT * FROM users WHERE user_email = ?");
$stmt->execute([$email]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function getUserByUsername($username){
global $db;
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function updateUser($userId, $name, $username, $email, $hashedPass, $isAdmin) {
global $db;
$stmt = $db->prepare("UPDATE users SET user_name = ?, username = ?, user_email = ?, user_hashedPass = ?, isAdmin = ? WHERE user_ID = ?");
$stmt->execute([$name, $username, $email, $hashedPass, $isAdmin, $userId]);
return "User updated successfully"; }
public function deleteUser($userId) {
global $db;
$stmt = $db->prepare("DELETE FROM users WHERE user_ID = ?");
$stmt->execute([$userId]);
return "User deleted successfully";
}
public function getAllUsers() {
global $db;
$stmt = $db->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
?>