beginTransaction(); try { $selectStmt = $pdo->prepare("SELECT id FROM users WHERE username = ?"); $insertStmt = $pdo->prepare("INSERT INTO users (username, password_hash) VALUES (?, ?)"); $updateStmt = $pdo->prepare("UPDATE users SET password_hash = ? WHERE id = ?"); $out = fopen($outputFile, 'w'); if ($out === false) { throw new RuntimeException('Failed to open output file for writing.'); } $seen = []; foreach ($lines as $line) { $username = trim($line); if ($username === '' || isset($seen[$username])) { continue; } $seen[$username] = true; $password = generatePassword($charset, $charsetLen, 6); $hash = password_hash($password, PASSWORD_BCRYPT); $selectStmt->execute([$username]); $user = $selectStmt->fetch(PDO::FETCH_ASSOC); if ($user) { $updateStmt->execute([$hash, $user['id']]); } else { $insertStmt->execute([$username, $hash]); } fwrite($out, $username . ':' . $password . PHP_EOL); } fclose($out); $pdo->commit(); echo "Done. Output: {$outputFile}\n"; } catch (Throwable $e) { $pdo->rollBack(); fwrite(STDERR, "Error: " . $e->getMessage() . "\n"); exit(1); } ?>