maanse
August 3, 2012, 2:26pm
1
Hi guys,
Im looking for a way to create a php script that when navigated to will automatically download a CSV file of the contents of a particular table. I have the Mysql Db set up but im not sure how to proceed for the csv download. The query it self will extract all data from yesterdays date.
Any suggestions.
bplaza
August 3, 2012, 6:58pm
2
probably you may have to write some php, or some code to extract csv.
Hi
Why not write it directly from MySQL:
SELECT id, name, email INTO OUTFILE '/tmp/My_Exported_Data.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY ‘\\\\’LINES TERMINATED BY '\
'
FROM users WHERE /* return rows based on Where clause */
<?php
$table=“”; // this is the tablename that you want to export to csv from mysql.
exportMysqlToCsv($table);
function exportMysqlToCsv($table,$filename = ‘export.csv’)
{
$csv_terminated = "
“;
$csv_separator = “,”;
$csv_enclosed = '”';
$csv_escaped = “\\”;
$sql_query = “select * from $table”;
// Gets the data from the database
$result = mysql_query($sql_query);
$fields_cnt = mysql_num_fields($result);
$schema_insert = '';
for ($i = 0; $i < $fields_cnt; $i++)
{
$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
$schema_insert .= $l;
$schema_insert .= $csv_separator;
} // end for
$out = trim(substr($schema_insert, 0, -1));
$out .= $csv_terminated;
// Format the data
while ($row = mysql_fetch_array($result))
{
$schema_insert = '';
for ($j = 0; $j < $fields_cnt; $j++)
{
if ($row[$j] == '0' || $row[$j] != '')
{
if ($csv_enclosed == '')
{
$schema_insert .= $row[$j];
} else
{
$schema_insert .= $csv_enclosed .
str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
}
} else
{
$schema_insert .= '';
}
if ($j < $fields_cnt - 1)
{
$schema_insert .= $csv_separator;
}
} // end for
$out .= $schema_insert;
$out .= $csv_terminated;
} // end while
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($out));
header("Content-type: text/x-csv");
//header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
echo $out;
exit;
}
?>
maanse
August 5, 2012, 9:27pm
5
Some great answers there, i shall give them a go, thanks.