Export Parts of MySQL Table to Excel CSV File Using PHP

PHP Tutorials

This is a quick snippet of code I created to dynamically pull a user-defined query from a MySQL database and export it the a CSV file.

{code type=php}

include (‘inc/connect.php’);

//define the table that you want to pull data from
$table = “table_name”;

//define the variables for your query
$query_variables = $_POST[‘id’];

//build your dynamic query
$query = “SELECT * FROM `”.$table.”` WHERE “.$query_variables.””;

$result = mysql_query(“SHOW COLUMNS FROM “.$table.””);
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row[‘Field’].”, “;
$csv_output .= “\n”;

$values = mysql_query(“$query”);
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].”, “;
$csv_output .= “\n”;

$filename = $file.”_”.date(“Y-m-d_H-i”,time());
header(“Content-type: application/vnd.ms-excel”);
header(“Content-disposition: csv” . date(“Y-m-d”) . “.csv”);
header( “Content-disposition: filename=”.$filename.”.csv”);
print $csv_output;



Leave a Reply

Your email address will not be published. Required fields are marked *

What's the Buzz?

Andy is a true top notch programmer with a great eye for design, style and balance. When I out source web development projects, I look for qualified and competent programmers that can understand the big picture, add value throughout entire process, and pays close attention to the details – Andy fits the bill.

Andy is well-versed in web development using various programming languages and CMS platforms. Andy is able to deliver a flawless website based on the creative vision and project requirements. He is able to do it on time and on budget.

I highly recommended Andy as a web developer and give him four stars on his professionalism.

- John LeDonne
LeDonne Creative