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’].”, “;
$i++;
}
}
$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;
exit;

?>

{/code}

Leave a Reply

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

What's the Buzz?

Andy is the consummate professional. He is sharp, creative, highly-skilled, and extremely responsive.  A true WordPress whiz. We are very pleased with our new website.

- Lauren McKibben
Incline Equity Partners