prepare("SELECT id FROM users WHERE email = ?"); $stmt->execute([$email]); if ($stmt->fetch()) { $errors['email'] = 'Email already exists.'; } } catch (PDOException $e) { $errors['db'] = "Database error: " . $e->getMessage(); } } if (empty($password)) { $errors['password'] = 'Password is required.'; } elseif (strlen($password) < 8) { $errors['password'] = 'Password must be at least 8 characters long.'; } // Check for role uniqueness: Bursar and Assistant Bursar if ($role === 'Bursar' || $role === 'Assistant Bursar') { try { $pdo = db(); $stmt = $pdo->prepare("SELECT id FROM users WHERE role = ?"); $stmt->execute([$role]); if ($stmt->fetch()) { // Using 'db' to show a general form error, as there's no specific field for this. $errors['db'] = "A user with the role '{$role}' already exists. Only one is allowed."; } } catch (PDOException $e) { $errors['db'] = "Database error while checking role uniqueness: " . $e->getMessage(); } } if (empty($errors)) { try { $pdo = db(); $hashed_password = password_hash($password, PASSWORD_DEFAULT); $sql = "INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, ?)"; $stmt = $pdo->prepare($sql); $stmt->execute([$name, $email, $hashed_password, $role]); $_SESSION['success_message'] = 'User created successfully.'; header("Location: users.php"); exit; } catch (PDOException $e) { $errors['db'] = "Database error: " . $e->getMessage(); } } $_SESSION['errors'] = $errors; $_SESSION['old_input'] = $_POST; header("Location: add_user.php"); exit; } header("Location: add_user.php"); exit;