简体   繁体   中英

Automatically add new rows with values to a csv file generated from mysql

i created a small script that i generating a csv file with a content from a mysql db. Everything is working fine but i am struggling with one issue... as you can see i am generating a file for a WooCommerce product import. My database contain's only some of items needed for the csv so i need to generate the other items automatically. So in example i like to add a row 'type' and add a value "simple" or 'in_stock" with a value '1' to all of the items. I am learning php and i am not sure how to add it to the while loop.

if (isset($_POST["export"])) {
    $connect = mysqli_connect("localhost", "root", "root", "dh_products");
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    $output = fopen("php://output", "w");

    fputcsv($output, array(
       'id',
       'type',
       'SKU',
       'Name',
       'Published',
       'Is featured?',
       'Visibility in catalog',
       'Short description',
       'Description',
       'dh_symmetry',
       'Date sale price starts',
       'Date sale price ends',
       'Tax status',
       'Tax class',
       'In stock?',
       'Stock',
       'Low stock amount',
       'Backorders allowed?',
       'Sold individually?',
       'Weight (kg)',
       'Length (cm)',
       'Width (cm)',
       'Height (cm)',
       'Allow customer reviews?',
       'Purchase note',
       'Sale price',
       'Regular price',
       'Categories',
       'Tags',
       'Shipping class',
       'Images',
       'Download limit',
       'Download expiry days',
       'Parent',
       'Grouped products',
       'Upsells',
       'Cross-sells',
       'External URL',
       'Button text',
       'Position',
      ));

    $query = "SELECT * from dh ORDER BY id DESC";

    $result = mysqli_query($connect, $query);

    while ($row = mysqli_fetch_assoc($result)) {
        fputcsv($output, $row);
    }

    fclose($output);
}

What kind of column do you need.

Add simply

,' ' as testcolumn 

to your select statement.

And before you make your

fputcsv($output, $row);

you change the value of that new cloumn

$row["testcolumn"} = xyz;
fputcsv($output, $row);

Of Course you also need to change:

fputcsv($output, array(

If you want the new Column at a specific place, you can't use

Select * anymore

For Static text, only to complete the answer, you simply add

,'some static text' as testcolumn 

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