Skip to content

Instantly share code, notes, and snippets.

@jaredrummler
Last active May 27, 2022 16:20
Show Gist options
  • Save jaredrummler/2bfcf48b48d3fefd50c2 to your computer and use it in GitHub Desktop.
Save jaredrummler/2bfcf48b48d3fefd50c2 to your computer and use it in GitHub Desktop.
<?php
$db_con = mysqli_connect("localhost", "username", "password", "database");
$result = $db_con->query('SELECT * FROM some_table');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysqli_num_fields($result);
$headers = array();
while ($fieldinfo = mysqli_fetch_field($result)) {
$headers[] = $fieldinfo->name;
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment