Trouble with fixing orphan users
The problem resides here:

SET @sqlstring = N'USE ' + @dbname
EXECUTE sp_executesql @sqlstring


What's happening is this executes - changes the database in the execution context for sp_executesql but will not change the parent context. Later on the code assumes this to be true by not continuing to use dynamic sql which means it'll run in the original database context.

IF EXISTS (SELECT dp.name  As Orphan_Users
                        FROM sys.database_principals dp
                        left join sys.server_principals sp
                        ON dp.sid=sp.sid 
                        WHERE sp.name IS NULL 
                        AND dp.type='S' AND 
                        dp.name NOT IN ('guest','INFORMATION_SCHEMA','sys'))

ALTER USER SomeUser WITH LOGIN = SomeUser
ALTER ROLE [db_backupoperator] ADD MEMBER [SomeUser]
ALTER ROLE [db_owner] ADD MEMBER [SomeUser]


This can be fixed by making it execute in the proper context by extending the dynamic sql.