Last active
August 29, 2015 14:06
-
-
Save duccoder/a5e03d98a49106f95be5 to your computer and use it in GitHub Desktop.
Get csv from table mysql use php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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