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?

In working with Andy, I was extremely impressed by his overall expertise and the “can-do” attitude with which he approached every phase of the project. While some designers may have become frustrated by working with multiple decision makers with limited web development knowledge, Andy was very understanding and strategic in his approach to finding very organized solutions to address our needs. I would highly recommend him!

- Allison Davies
Ten United