Skip to content

Instantly share code, notes, and snippets.

@Amantel
Forked from navitronic/export-table.php
Last active August 29, 2015 14:07
Show Gist options
  • Save Amantel/88fbfc7d01c94367359b to your computer and use it in GitHub Desktop.
Save Amantel/88fbfc7d01c94367359b to your computer and use it in GitHub Desktop.
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
$dbname = 'dbname';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$fields=[];
$csv=[];
$tablename = 'table';
$sql = 'SHOW COLUMNS FROM `'.$tablename.'`';
$stmt = $dbh->query($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
array_push($fields, $row['Field']);
}
array_push($csv, $fields);
$sql = 'SELECT * FROM `'.$tablename.'`';
$stmt = $dbh->query($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
#add BOM for russian xls
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
foreach ($csv as $row) {
fputcsv($fp, $row);
}
fclose($fp);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=export.csv");
header("Pragma: no-cache");
header("Expires: 0");
readfile('file.csv');
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment