Write custom column names to query result file

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I'm a relative newbie to PHP, but have been able to put together some PHP
code to generate a CSV/XLS file from a Query result. Now, I would like to
include custom column names instead of the MySQL column table names. I know
that there are codes to generate tabs and carriage returns, but can't find
anything about including "commas" in a string to output to the file to
separate the custom field names. I'd appreciate some help with a line of
code to insert those custom column names like:

First Name | Last Name | DOB | etc.


Joe G.

The generated file is set to the company name + date.xls and output the data
correctly. My PHP code is:

// Remove spaces from Company Name
$trim_name = str_replace(" ", "", $co_name);
echo $file_name;
// Connect to Database
@mysql_select_db($database) or die( "Unable to select database");
// Find the Number of Fields
$select = "SELECT * FROM employee WHERE co_name='$co_name'";
$export = mysql_query($select);
$fields = mysql_num_fields($export);
// Extract Database Fields
for ($i = 0; $i < $fields; $i++) {
    $header .= mysql_field_name($export, $i) . "\t";
// Extract your 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);
// Default Message
if ($data == "") {
    $data = "\n(0) Records Found!\n";
$fp = fopen($file_name,"a"); // $fp is now the file pointer to file
$fp = fopen($file_name,"a");
fwrite($fp,$data); // Write information to the file
fclose($fp);  // Close the file
echo "File saved successfully";
} else {
echo "Error saving file!";
echo "Use your Browser Back Button to Return";

Re: Write custom column names to query result file

Joe Gazda wrote:
Quoted text here. Click to load it
like to
I know

Just replace  "\t" with ",".  That's it.

Quoted text here. Click to load it

OK, right now you have:

Quoted text here. Click to load it

Just replace it with

$header = "First Name,Last Name,DOB,etc.";


Re: Write custom column names to query result file

Substituting the code yields the field name string in the first cell of MS
 I've just decided to have the client "import" the data fields into an
existing Excel Spreadsheet with the Custom Field Names already in place.
Thanks for you help, anyway.

Quoted text here. Click to load it

Site Timeline