Sharmi
Sharmi

Reputation: 9

How to import the column value as comma from mysql data to csv file using php

In csv file i need a comma in column value.

Here is the mysql query:

$q_pack = "select p.filename, p.version, dt.name as external,p.internal
          from cert c 
            join packages p on c.package_id=p.id 
            left join documents dt on p.id=dt.package_id 
            left join documents doc on doc.id=d.document_id 
          where c.certificate_id=100";

$res_pack = db_query($q_pack);
if ($res_pack){
$fp = fopen('sample.csv', 'w');
$title = "filename, version, external,internal";
fwrite($fp, $title);
while ($pack_row = db_fetch_object($res_pack)){
fwrite($fp, "\n");
foreach ( $pack_row as $line ) {
$val = $line.',';
fwrite($fp, $val);}}
fclose($fp);}

Here column name as "external" and the value is joe,bob. In mysql table the value of external return as joe,bob, but in csv file it displayed as joe is in one column and bob is in another column.

Please refer the screenshot for CSV file. Csv file

Upvotes: 0

Views: 86

Answers (1)

Alexey Chuhrov
Alexey Chuhrov

Reputation: 1787

You should use fputcsv() it will automatically enclosure your fields with commas in double quotes

$res_pack = db_query($q_pack);
$fp = fopen('sample.csv', 'w');
fputcsv($fp, ['filename', 'version', 'external', 'internal']);
while ($pack_row = db_fetch_array($res_pack)) {
    fputcsv($fp, $pack_row);
}
fclose($fp);

So in this case, sample row:

array(
    'filename' => 'file',
    'version' => 10
    'external' => 'foo,bar'
    'internal' => 'baz'
);

will be encoded as follows file,10,"foo,bar",baz

Read more: http://php.net/manual/en/function.fputcsv.php

Upvotes: 2

Related Questions