Skip to content

Instantly share code, notes, and snippets.

@fieldoffice
Created March 14, 2015 11:20
Show Gist options
  • Save fieldoffice/ccb6f339b17671a9c7db to your computer and use it in GitHub Desktop.
Save fieldoffice/ccb6f339b17671a9c7db to your computer and use it in GitHub Desktop.
Export to CSV (MySQL)
<?php
$conn = mysqli_connect('localhost','user','pw') or die(mysqli_error());
$db=mysqli_select_db($conn,'database') or die(mysqli_error());
$filename = 'filename-' . date("d-m-Y") . '.csv';
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Content-Description: File Transfer' );
header( 'Content-type: text/csv' );
header( "Content-Disposition: attachment; filename={$filename}" );
header( 'Expires: 0' );
header( 'Pragma: public' );
$select_table=mysqli_query($conn,'select * from table');
$rows = mysqli_fetch_assoc($select_table);
if ($rows) {
getcsv(array_keys($rows));
}
while($rows)
{
getcsv($rows);
$rows = mysqli_fetch_assoc($select_table);
}
function getcsv($no_of_field_names)
{
$seperate = '';
foreach ($no_of_field_names as $field_name)
{
if (preg_match('/\\r|\\n|,|"/', $field_name))
{
$field_name = '' . str_replace('', $field_name) . '';
}
echo $seperate . $field_name;
$seperate = ',';
}
echo "\r\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment