Skip to content

Instantly share code, notes, and snippets.

@duccoder
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duccoder/a5e03d98a49106f95be5 to your computer and use it in GitHub Desktop.
Save duccoder/a5e03d98a49106f95be5 to your computer and use it in GitHub Desktop.
Get csv from table mysql use php
<?php
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'blog'; //database name
$table= 'users'; //table name you need export
$fileName = 'export';
//try connect
$dbLink = mysql_connect($dbHost, $dbUser, $dbPass) or die('Can not connect.' . mysql_error());
mysql_select_db($dbName) or die('Can not connect.');
$csvFileContent = '';
//first row is header name column
$columns = mysql_query('SHOW COLUMNS FROM ' . $table);
$i = 0;
if (mysql_num_rows($columns) > 0) {
while ($row = mysql_fetch_assoc($columns)) {
$csvFileContent .= $row['Field'] . ',';
$i++;
}
}
//rows content data of table
$csvFileContent .= "\n";
$values = mysql_query('SELECT * FROM ' . $table);
while ($rows = mysql_fetch_row($values)) {
for ($j = 0; $j < $i; $j++) {
$csvFileContent .= $rows[$j] . ', ';
}
$csvFileContent .= "\n";
}
//file export name format: fileName_timeStamp
$time = new \DateTime();
$fileName = $fileName . '_' . $time->getTimestamp();
//response file csv
header('Content-type: application/vnd.ms-excel');
header('Content-disposition: filename=' . $fileName . '.csv');
print $csvFileContent;
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment