beginTransaction(); $createdCount = 0; $errorCount = 0; $errors = []; // Get all roles from the database $stmt = $pdo->query("SELECT id, name FROM roles"); $roles = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); foreach ($csvData as $rowIndex => $row) { $username = $row[0] ?? null; $password = $row[1] ?? null; $roleName = $row[2] ?? null; if (empty($username) || empty($password) || empty($roleName)) { $errorCount++; $errors[] = "Row " . ($rowIndex + 2) . ": Invalid data."; continue; } if (!in_array($roleName, $roles)) { $errorCount++; $errors[] = "Row " . ($rowIndex + 2) . ": Role '".htmlspecialchars($roleName)."' does not exist."; continue; } $roleId = array_search($roleName, $roles); try { $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?"); $stmt->execute([$username]); if ($stmt->fetch()) { $errorCount++; $errors[] = "Row " . ($rowIndex + 2) . ": User '".htmlspecialchars($username)."' already exists."; continue; } $hashedPassword = password_hash($password, PASSWORD_DEFAULT); $stmt = $pdo->prepare("INSERT INTO users (username, password, role_id) VALUES (?, ?, ?)"); $stmt->execute([$username, $hashedPassword, $roleId]); $createdCount++; } catch (PDOException $e) { $errorCount++; $errors[] = "Row " . ($rowIndex + 2) . ": Database error."; } } if ($errorCount > 0) { $pdo->rollBack(); $_SESSION['flash_message'] = [ 'type' => 'danger', 'message' => "User import failed with {$errorCount} errors.", 'errors' => $errors ]; } else { $pdo->commit(); $_SESSION['flash_message'] = [ 'type' => 'success', 'message' => "Successfully created {$createdCount} users." ]; } } else { $_SESSION['flash_message'] = [ 'type' => 'danger', 'message' => 'Invalid CSV header. Expected: username,password,role' ]; } } else { $_SESSION['flash_message'] = [ 'type' => 'danger', 'message' => 'Error uploading file.' ]; } header('Location: manage_users.php'); exit(); } ?> Manage Users - <?php echo htmlspecialchars($projectName); ?>

Manage Users

Import Users from CSV

Upload a CSV file with the following columns: username, password, role.