Export MySQL data to csv using php

A lot of clients requires to export the data from database to csv. So i decided to add an post related to this
on export mysql data to csv using php

Below is the code on how we can do this make sure you dont have any out put before the code below,If so it produces an header already sent error


/* Database connection information */
$gaSql['user']       = $config['username'];
$gaSql['password']   = $config['password'];
$gaSql['db']         = $config['dbname'];
$gaSql['server']     = $config['host'];

/*
 * MySQL connection
 */
$gaSql['link'] =  mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) or
die( 'Could not open connection to server' );

mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );
/*
 * Remove upto this if you already have database connection
 */
$select = "SELECT * FROM table ";

$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 ) . ",";
}

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

Leave a Reply

Your email address will not be published.