Ok so I won't directly answer your question as I honestly don't believe it will help you in the long run, I will give you some pointers though...
1) Your script is open to an SQL injection attack - if you carry on going this way its highly likely that anybody can export any part of your database with a carefully crafted SQL injection attack. - Read here: http://shishirceh.blogspot.de/2011/06/sql-injection-beginners-tutorial.html if you don't know what SQL injection is.
2) Looking at your code I'd guess that you're pretty new to PHP (we all have to start somewhere right). Coding "vanilla" PHP can be a pain in the ass, luckily people in the PHP community have created "frameworks" that you can work with which take a lot of the risk out of creating PHP applications. I like using Symfony personally and its really easy to get started with it, tuturial: http://symfony.com/doc/current/quick_tour/the_big_picture.html
3) The way you are using MySQL is quite outdated and not compatible with the latest versions of PHP. Take a look here for a better alternative: http://www.w3schools.com/php/php_mysql_prepared_statements.asp
4) The way you are programming (Mixing the bits the user sees and the bits that make the website work) will lead you to a whole lot of problems (security, compatibility with other libraries, sanity) Frameworks will take care of this for you and give you a specific place to put these elements. However to really take advantage of PHP and be a "good" programmer you should really learn object orientated programming first - I'd recommend you read through this book: http://www.ycit-he.org/files/Resources/PHP%20Objects,%20Patterns,%20and%20Practice.pdf
5) If you go down the symfony route they ahve a filesytem component for writing to files: http://symfony.com/doc/current/components/filesystem/introduction.html
6) With Symfony you can easily force a user to download the file once you have generated it
// Generate response
$response = new Response();
// Set headers
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition', 'attachment; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
// Send headers before outputting anything
$response->sendHeaders();
$response->setContent(file_get_contents($filename));
Hope this helps,
Mark
` with `\n` and move the `echo` into a conditional. – chris85 May 31 '16 at 14:40