I have to do something very similar: few users of our site asked to change their login. I have tried changing it fiddling via sql, altering the ezuser table.
The problem with that approach is that the user home folder keeps using the same old login name.
Would your code work in my case too? How do you use it: do I need a php page or a script?