Link to home
Start Free TrialLog in
Avatar of sulentho
sulentho

asked on

csv download issue

I am have written the following script to download results from my mysql query to csv. The code

define(db_host, "localhost");
define(db_user, "username");
define(db_pass, "passwd");
define(db_link, mysql_connect(db_host,db_user,db_pass));
define(db_name, "db_name");
mysql_select_db(db_name);

$select = "SELECT m.mail_email,t.mail_type FROM mailing AS m, mail_type AS t WHERE m.mail_type=t.type_id ORDER BY m.mail_type ASC";                
$export = mysql_query($select);
$fields = mysql_num_fields($export);

for ($j = 0; $j < $fields; $j++) {
    $header .= mysql_field_name($export, $j) . "\t";
}
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);

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

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=emails.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

This code dumps out the results which is perfect but now I want the results to start from the second row and the first row to have prefilled column name --- Email Address (column 1), Type (column 2). I will really appreciate it someone can tweak my code to allow for this functionality. Thanks

Sulen
ASKER CERTIFIED SOLUTION
Avatar of Raynard7
Raynard7

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sulentho
sulentho

ASKER

Thank you sir, worked great.