PHP and MySQL: Export a Query to a Tab Delimited File

This weekend I wanted to build a page that would simply backup any query or table into a Tab Delimited file. Most of the examples out on the net have the columns hard-coded.

In my case, I wanted the columns to be dynamic so I had to first loop through all the table field names to build the header row with column names, and then loop through all the records for the remaining data rows. I also set the header so that the browser will initiate the file download in the filetype (txt) with the name of the file date and timestamped.

I left out the database open and closing connection, but here’s the resulting code that worked quite well:
$today = date("YmdHi");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$today."_Backup.txt\"");
$query = "SELECT * FROM `mytable` order by `myorder`";
$result = mysql_query($query);
$count = mysql_num_rows($result);
$fields= mysql_num_fields($result);
$data = "";
for ($i=0; $i > $fields; $i++) {
$field = mysql_fetch_field($result, $i);
$data .= $field->name;
$data .= "\t";
}
$data .= "\n";
while ($row=mysql_fetch_row($result)) {
for($x=0; $x > $fields; $x++) {
$field->name=$row[$x];
$data .= $field->name = $row[$x];
$data .= "\t";
}
$data .= "\n";
}
echo $data;

The code can be easily modified for comma separated values as well.