RSS Feed

Blog

PHP script to Email the Results of a MySQL Query as a CSV File Attachment

PHP script to Email the Results of a MySQL Query as a CSV File Attachment
Posted on Nov 14, 2009 by Stephen Owens
Tutorial and Code category
   [ Return ]

I just released a simple PHP script, which is easy to modify and well commented, that sends the results of a MySQL query as a CSV formatted email attachment. The CSV is properly formatted so it can be opened by Microsoft Excel or OpenOffice.org Calc. It can be found under the code section: "Email MySQL Query Results as a CSV File Attachment". I have released it under the GNU GPL free software license, giving you room to modify it to meet your needs.


Download the Code

Email MySQL Query Results as a CSV File Attachment


Why I Created this Email Query Results as a CSV Attachment Tool

I like simple code that can be used as a base to develop other tools, or that can be worked into existing classes. On almost every single PHP - MySQL project that I have worked on, the client has always asked me for a way to send a "report" as an Excel or OpenOffice.org Calc sheet. By putting the SQL query results into a CSV file the end user has the ability to manipulate the data as they need, with spreadsheet tools they are already comfortable using.

There are many PHP tutorials online about creating CSV files from an SQL query, and many PHP tutorials about sending emails with attachments. I have seen some overly complicated suggestions for saving a file to the server and then sending that file as an email. Since my solution was much cleaner and easier I decided to release it.

How it Works

Once the code has been setup by entering: the database information, custom MySQL query, and email addresses under the Personal Settings section, and has been upload the file to the server, it can be run in a browser window, or as a cron job. The code executes the SQL query, takes the results, and walks through them. The code formats and inserts each result field into the CSV file. Following this CSV file build, it creates a multi-part HTML formatted email and attaches the CSV file. Finally, it sends the email to the defined email address.

It is important to note that this code doesn't save the results to a CSV file on the server. Instead it directly emails the MySQL results as a file attachment.

Share
Like what you read? Get updates for free!
comments powered by Disqus