Web Development Blog

Export MySQL table into CSV using PHP

Here is code to download MySQL table into CSV and force browser to download csv file.

<?
// Database Connection
include "dbconnect.php";

$sSQL="SELECT column1 AS 'column 1 name',
                column2 AS 'Column 2 / something'
    FROM tablename
    WHERE column1=1"
;
$result=mysql_query($sSQL) or die ("MySQL err: ".mysql_error()."<br />".$sSQL);                
$columns_total mysql_num_fields($result);

$fileLine=0// For output array
for ($i 0$i $columns_total$i++)
{
    
//First line with the headers
    
$list[$fileLine][]= mysql_field_name($result$i);;
}

while (
$row mysql_fetch_array($result))
{
    
//Switch to next line
    
$fileLine++;
    for (
$i 0$i $columns_total$i++)
    {
        
//REad all rows
        
$list[$fileLine][]= $row[$i];
    }
}

//File path, make sure that you have proper permissions to write in the file
$tmpFile=$_SERVER['DOCUMENT_ROOT'].'/dat/file.csv';

//Create / open file
$fp fopen($tmpFile'w');

//Delete all existing file content
file_put_contents($tmpFile"");


foreach (
$list as $fields)
{
    
fputcsv($fp$fields);
}
fclose($fp);

$filename "contentHistory_".date("Y-m-d").".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
readfile$tmpFile );
exit;

//Optional code to delete file from the system:
//unlink($tmpFile)'

?>

Associated tags:  MySQL, CSV, Download, Export

Add Comment:

CAPTCHA