EnderX 352 Posting Shark

I've been given a piece of buggy code to attempt reviving. At the moment, every time I run it, I'm getting this error:

Database handle destroyed without explicit disconnect.

A quick google search reveals that this indicates I'm not closing a connection. I had trouble figuring out why I was getting this error until I realized that there appear to be two connections getting opened by the program. The program itself runs a select statement, then inside a loop drawing from that, is supposed to delete the files with the values given by the select.

In addition to throwing the 'disconnect' error, I'm not getting any of my records deleted except for the very first thing it calls. Do I need to explicitly close and reopen the connection after every action it's supposed to take, or are my problems likely to lie elsewhere?

Any advice on this will be greatly appreciated.