Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

mysql data to excel

Status
Not open for further replies.

dugen

Programmer
Jun 16, 2003
59
US
I have a script that extracts data from a mysql database to an excel sheet. I was wondering how do I get the fields from the table to show up as the column names in the excel spreadsheet?.

<?php
//Count the number of fields in the database

$select = "SELECT * FROM form_data";
$export = mysql_query($select);
$fields = mysql_num_fields($export);


//start a loop to extract all the field names from the db

for ($i = 0; $i < $fields; $i++) {
$header .= mysql_field_name($export, $i) . "\t";
}


//extracting all the data

while($row = mysql_fetch_row($export)) {
$line = '';
foreach($row as $value) {
if ((!isset($value)) OR ($value == "")) {
$value = "\t";
} else {
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim($line)."\n";
}
$data = str_replace("r","",$data);


//Check the database for data

if ($data == "") {
$data = "\n(0) Records Found!n";
}


//prompts user to save the spread sheet

header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=extraction.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$headern$data";
?>

 
two methods

method 1
Code:
$fields = mysql_query("Show fields from form_data");
$fieldnames ="";
while ($field_data = mysql_fetch_assoc($fields)):
  $fieldnames .= $field_data['Field'] ."\t";
endwhile;
$fieldnames = rtrim($fieldnames, "\t") . "\r\n";

or
change the mysql_fetch_row to mysql_fetch_assoc and extract the fieldnames from the array keys.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top