Search code examples
phpmysqlexcelcsv

Exporting MySQL Data Into Excel Broken By Comma


I have this code :

$sql = "SELECT  ...
        FROM    ...
        WHERE   ...;

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password);
$Db = @mysql_select_db($DB_DBName, $Connect);
$result = @mysql_query($sql,$Connect);
$file_ending = "xls";

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");

$sep = "\t"; //tabbed character
while($row = mysql_fetch_row($result))
{
    $schema_insert = "";
    for($j=0; $j<mysql_num_fields($result); $j++)
    {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
    $schema_insert .= "\t";
    print(trim($schema_insert));
    print "\n";
}   

it works perfectly if data on each columns doesn't contains comma. but when it has comma, then it will become separator and exported column and data isn't same as SQL result.

how to ignore comma on MySQL result so it can be exported as Excel file? thank you.


Solution

  • you can just add quotes to surround your text:

    $sql = "SELECT  ...
            FROM    ...
            WHERE   ...";
    
    $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password);
    $Db = @mysql_select_db($DB_DBName, $Connect);
    $result = @mysql_query($sql,$Connect);
    $file_ending = "xls";
    
    header("Content-Type: application/xls");    
    header("Content-Disposition: attachment; filename=$filename.xls");  
    header("Pragma: no-cache"); 
    header("Expires: 0");
    
    $sep = "\t"; //tabbed character
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result); $j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= '"'."$row[$j]".'"'.$sep;  // changes on this line
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t";
        print(trim($schema_insert));
        print "\n";
    }