Just set your code to run the final closing routine after the loop finishes, this will need you to set variables for the record data if you want to be able to use the final data outside the loop, but if not it is very simple. A simple section in the loop could also set a variable like $if_found to 1 if any data is found, initialise it to 0 before the loop. Use an if on this to control whether the final routine runs.
You can use mysql_num_rows to get the number of results a query returns, and work with that: