Jump to content

export query to CSV


will35010

Recommended Posts

I have this code that is supposed to export the results of this query into a CSV. When I run the code in Firefox, it works perfectly. The only browser that it doesn't work in is IE. It opens an HTML page with the results on the page instead of prompting to download the CSV. Can anyone help me out?

 

<?php
//code to export report to excel
if(isset($_GET['date'])){
    
include('../inc/db.php');    
    
if (!$link = mysql_connect($dbhost, $dbuser, $dbpass)) {
    echo 'Could not connect to mysql';
    exit;
}

if (!mysql_select_db($dbname, $link)) {
    echo 'Could not select database';
    exit;
}
$date = $_GET['date']; 

$select = "SELECT patients.lname, patients.fname, patients.dob, patients.sex, visit_data.cc, 
FROM_UNIXTIME(visit_data.reg_time), FROM_UNIXTIME(visit_data.discharged_time), visit_data.disposition, visit_data.leftby 
FROM patients, visit_data WHERE discharge_date = '$date' AND patients.patientid = visit_data.patientid";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

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

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                            
        if ( ( !isset( $value ) ) || ( $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=DailyLog.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.