ultraloveninja Posted November 6, 2010 Share Posted November 6, 2010 Hey there! I was wondering if it's possible to change the header columns on a CSV export from a MySQL select? Currently it pulls the information that I need and creates a CSV file, but the first row is the column name from the database and I am not sure if there is a way to change that when the CSV is created. Here's the export script that I am using: <?php // Connect database require_once 'library/config.php'; require_once 'library/common.php'; $csv_terminated = "\n"; $csv_separator = ","; $csv_enclosed = '"'; $csv_escaped = "\\"; $sql_query = "SELECT * FROM tbl_order, tbl_order_item, tbl_product WHERE tbl_order.od_id = tbl_order_item.od_id AND tbl_order_item.pd_id = tbl_product.pd_id AND tbl_order.od_status = 'Paid'"; // Gets the data from the database $result = mysql_query($sql_query); $fields_cnt = mysql_num_fields($result); $schema_insert = ''; for ($i = 0; $i < $fields_cnt; $i++) { $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes(mysql_field_name($result, $i))) . $csv_enclosed; $schema_insert .= $l; $schema_insert .= $csv_separator; } // end for $out = trim(substr($schema_insert, 0, -1)); $out .= $csv_terminated; // Format the data while ($row = mysql_fetch_array($result)) { $schema_insert = ''; for ($j = 0; $j < $fields_cnt; $j++) { if ($row[$j] == '0' || $row[$j] != '') { if ($csv_enclosed == '') { $schema_insert .= $row[$j]; } else { $schema_insert .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed; } } else { $schema_insert .= ''; } if ($j < $fields_cnt - 1) { $schema_insert .= $csv_separator; } } // end for $out .= $schema_insert; $out .= $csv_terminated; } // end while $now = date("m-d-Y"); $output_file = $now."_export-labels.csv"; file_put_contents($output_file,$out); header('Content-Type: application/octet-stream; name="' . $output_file . '"'); header('Content-Disposition: inline; filename="' . $output_file . '"'); readfile($output_file); //header('Content-type: application/csv'); //header('Content-Disposition: attachment; filename="export.csv"'); //readfile('export.csv'); ?> More than anything, I just want to know if it's possible or not. Thanks! Quote Link to comment Share on other sites More sharing options...
BlueSkyIS Posted November 7, 2010 Share Posted November 7, 2010 yes, it is possible. either replace the code that is writing the column names now with code that puts in your own column names, or modify the SQL to use aliases for column names. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.