Exporting is IMO the best solution as well. No point in reinventing the wheel on this.
You have other serious problems if this is taking you like 1 - 2 days. This code's job is to write a single line into the CSV file, and what will be the last record of the query. Even if you have only 1 byte of memory left, I can't see 15K records taking 2 days to iterate through. If you only want the last record appended, than simply query with a LIMIT 1 and order in reverse.
Or, you could post the code you actually have in use.