Sunday, February 26, 2023

exporting to csv download from php

Following https://mehulgohil.com/blog/how-to-export-data-to-csv-using-php/

In our case, the required code was something like this:

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=filemastercsv_export.csv');
require("SessionCheck.php");
require("Constants.php");

$output = fopen( 'php://output', 'w' );
ob_end_clean();
$query= "select * from our_table_master f  where f.fileId > 50900 order by f.fileId";

$dbcon= mysql_connect($DBHOST,$DBUSER,$DBPASSWORD);

if(!$dbcon)
{
echo "Unable to connect to database !";
return;
}

mysql_select_db($DBNAME);

$totalrows= 0;

$result= mysql_query($query);

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

while ($row = mysql_fetch_row($result)) {

    fputcsv($output, $row);

}

mysql_free_result($result);

mysql_close($dbcon);

exit;



No comments:

Post a Comment