As others have mentioned we seem to be missing some code here.
However - to give a (potentially) different type of solution - it would seem that you should be able to do this in a single SQL statement. I can't do it now because I don't know what @old is, nor what $i is supposed to be (though I suspect that $i == scalar(@old)).
Michael