Wednesday, February 28, 2018

Export sql table to csv format in php.

<?php 
//First create db connection.
$output = "";
$sql = mysql_query("select col1,col2,col3 from table_name where 1");
$columns_total = mysql_num_fields($sql);
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysql_field_name($sql, $i);
$output .= '"'.$heading.'",';
}
$output .="\r\n";
while ($row = mysql_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
$filename = "Vendor-data-export.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
?>

No comments:

Post a Comment