简体   繁体   中英

php export DB to csv for excel

So this is my db design

tbl.fileparent (fp_id, fp_name) //e.g dress_A
tbl.properties (prop_id, prop_name) //e.g color, size
tbl.details (details_id, fp_id (FK), prop_id (FK), values) //e.g dress_A color:red, size:M

I need to create a csv file that will combine those 3 tbls. I know we need to execute something like:

SELECT a.fp_name, b.prop_name, c.values FROM tbl.fileparent a, tbl.properties b, tbl.details c WHERE c.fp_id=a.fp_id AND c.prop_id=b.prop_id

But it will produce something like this

|fp_name | prop_name | values |
|dress_A | color     | red    |
|dress_A | size      | M      |

I need to make the table output (csv) format become like this

|fp_name | color | size |
|dress_A | red   | M    | 

is that possible?

Thanks

CSV is like text file, but columns are divide by for example commas. To make this you have to fetch all date and make string in loop where begin part define columns names.

For example:

$csv = "fp_name,color,size\n";
foreach ($data_from_db as $element)
{
    $csv .= $element->fp_name.",".$element->color.",".$element->size."\n";
}

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=file_name.csv;" );
header("Content-Transfer-Encoding: binary");

echo($csv);

At now, you can download file and import into fe. Excel where divider is comma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM