Skip to content

Instantly share code, notes, and snippets.

@BrunIF
Forked from navitronic/export-table.php
Created August 30, 2012 15:21
Show Gist options
  • Select an option

  • Save BrunIF/3530720 to your computer and use it in GitHub Desktop.

Select an option

Save BrunIF/3530720 to your computer and use it in GitHub Desktop.
MySQL table to csv
<?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);
$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();
$csv = array();
while($row = $stmt->fetch(PDO::FETCH_NUM))
{
array_push($csv, $row);
}
$fp = fopen('file.csv', 'w');
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