can you specify what you mean by "exit"? maybe a silly question, but the reason why i'm asking is that slurping in the data from the database and grouping them really won't take much time. but the ... 7 nested for loops by which you write the data to the text file, will probably really not be the fastest approach.
besides, doesn't SQL offer lots of means for the task you are performing? and for MySQL, if you /Tee your results to an outfile...?