in reply to the final thorn in your toe

You have one $row variable, and you use it for both reading and writing the data. So data is read from and written to the same row. Maybe you should have a second variable for writing the rows (call it something besides $row), and only increment it when you have written a row?