Skip to content

Instantly share code, notes, and snippets.

@seanmcn
Last active August 29, 2015 14:10
Show Gist options
  • Save seanmcn/66d20cb68110ccb3c0a5 to your computer and use it in GitHub Desktop.
Save seanmcn/66d20cb68110ccb3c0a5 to your computer and use it in GitHub Desktop.
Converts mySQL data to CSV data
<?php
/* Database Info */
$server = "localhost";
$username = "username";
$password = "password";
$databaseName = "databaseName";
/* Table we want to export */
$tableName = "tableName";
/* Optional WHERE Statement */
//$whereStatement = "WHERE field = value";
$whereStatement = "";
/* Filename we want to save as */
$fileName = "example.csv";
/* Database Connection and result */
$dbConnection = mysqli_connect($server,$username,$password,$databaseName);
$dbResult = $dbConnection->query("SELECT * FROM ".$tableName." ".$whereStatement);
$fileOpen = fopen('php://output', 'w');
$headers[] = "Column Header 1";
if ($fileOpen && $dbResult) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$fileName.'"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fileOpen, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fileOpen, array_values($row));
}
die;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment