Skip to content

Instantly share code, notes, and snippets.

@guy4261
Created July 4, 2012 22:20
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 guy4261/3049801 to your computer and use it in GitHub Desktop.
Save guy4261/3049801 to your computer and use it in GitHub Desktop.
Download mysql table as TSV
<?php
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="default-filename.txt"');
$newline = "\r\n";
$delimiter = "\t";
$db_host = 'localhost';
$db_user = "web";
$db_pwd = '';
$dbname = 'results';
$table = 'questionnaire';
if (array_key_exists('dbname',$_GET))
{
$dbname = $_GET['dbname'];
}
if (array_key_exists('table',$_GET))
{
$table = $_GET['table'];
}
$db = mysql_connect($db_host, $db_user, $db_pwd) or die(mysql_error());
mysql_select_db($dbname, $db) or die(mysql_error());
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
// printing table headers
$field = mysql_fetch_field($result);
echo "{$field->name}";
for($i=1; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "${delimiter}{$field->name}";
}
echo "$newline";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "${row[0]}";
for($i=1; $i<$fields_num; $i++){
echo "${delimiter}${row[$i]}";
}
echo "$newline";
}
mysql_free_result($result);
mysql_close($db);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment