0

I am trying to open .csv file but when I open it Iam not getting any data but only getting headers.

The below is the module file for that particular csv file.The file getting downloaded but when I open the file only headings being visible but not the data.

<?php

define('BIOTWEAKS_AU_ONLY_SETTINGS', 'a:6:{s:4:"view";a:4:{i:0;i:5;i:1;i:7;i:2;i:4;i:3;i:3;}s:8:"view_own";a:2:{i:0;i:5;i:1;i:3;}s:6:"update";a:1:{i:0;i:3;}s:10:"update_own";a:1:{i:0;i:3;}s:6:"delete";a:1:{i:0;i:3;}s:10:"delete_own";a:1:{i:0;i:3;}}');
define('BIOTWEAKS_NZ_ONLY_SETTINGS', 'a:6:{s:4:"view";a:4:{i:0;i:5;i:1;i:7;i:2;i:6;i:3;i:3;}s:8:"view_own";a:2:{i:0;i:5;i:1;i:3;}s:6:"update";a:1:{i:0;i:3;}s:10:"update_own";a:1:{i:0;i:3;}s:6:"delete";a:1:{i:0;i:3;}s:10:"delete_own";a:1:{i:0;i:3;}}');


function biotweaks_menu() {
  $items = array();

  $items['admin/upload-product-csv'] = array(
      'title' => 'Upload product CSV file',
      'page callback' => 'drupal_get_form',
          'page arguments' => array('biotweaks_form'),
      'access arguments' => array('access content'),
      'type' => MENU_CALLBACK
    );

  $items['admin/upload-product-csv-download'] = array(
    'page callback' => 'biotweaks_product_csv_download',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function biotweaks_perm() {
    return array('true');
}

function biotweaks_form() {
    $form['description'] = array(
        '#type' => 'markup',
        '#value' => t('Please make sure that the CSV file you upload is in the right format with the columns in the correct order. If you are unsure, please contact the website administrator.'),
    );
    $form['download'] = array(
        '#type' => 'markup',
        '#value' => '<p><a href="/admin/upload-product-csv-download">Download a CSV of the current products</a></p>',
    );
    $form['csv'] = array(
        '#type' => 'file',
        '#title' => 'CSV file',
    );

    $form['#attributes'] = array('enctype' => "multipart/form-data");

    $form['submit'] = array('#type' => 'submit', '#value' => t('Upload CSV') );
    return $form;
}

function biotweaks_product_csv_download() {

    $fpath = '/home/biolab/public_html/';
    $fname = 'products.csv';

    $output_file = true;

    if ($output_file) {
        $fp = fopen($fpath.$fname, 'w');
    }


    $header = array('Product Code', 'Product Description', 'Size', 'Pallet Qty', 'DG Class', 'Category ID', 'Category Name', 'Subcategory Name', 'Subsubcategory Name', 'AU Case Price (ex. GST)', 'AU Price List 21', 'AU Price List 22', 'AU Price List 23', 'AU Price List 24', 'AU Price List 25', 'AU Price List 26', 'AU Price List 27', 'NZ Case Price (ex. GST)', 'NZ Price List 21', 'NZ Price List 22', 'NZ Price List 23', 'NZ Price List 24', 'NZ Price List 25', 'NZ Price List 26', 'NZ Price List 27', 'Image directory', 'Image filename');


    if ($output_file) {
        fputcsv($fp, $header);
    }

    $q = db_query('SELECT fid, price from {uc_fees}');
    global $fees;
    $fees = array();
    while ($r = db_fetch_array($q)) {
        $fees[] = $r;
    }

    function get_fee($fid) {
        global $fees;
        foreach ($fees as $fee) {
            if ($fid == $fee['fid']) {
                return $fee['price'];
            }
        }
        return 0;
    }

    $sql = "SELECT  n.status, n.nid,  n.title, tn.tid, ucp.model, ucp.sell_price,  upp.price,  ca.settings FROM  {uc_products} as ucp,  {term_node} as tn,  {node} as n left join {uc_price_per_role_prices} as upp on n.nid = upp.nid left join {content_access} as ca on n.nid = ca.nid   WHERE  ucp.nid = n.nid and  n.nid = tn.nid  AND n.nid=1452 and n.status = 1 ORDER BY tn.tid";
    $q = db_query($sql);

//print_r(db_fetch_array($q));exit;
    while ($r = db_fetch_array($q)) {

    echo '<pre>';
    //print_r($r);exit; 

        $parents = taxonomy_get_parents_all($r['tid']);
        $parent_count = count($parents);

        $fields = array();
        for ($i = 0; $i<26; $i++) {
            $fields[] = '';
        }
        $fields[0] = $r['model'];
        $fields[1] = $r['title'];
        $fields[5] = $r['tid'];
        $fields[6] = $parents[$parent_count-1]->name;
        $fields[7] = ($parent_count > 1) ? $parents[$parent_count - 2]->name : '';
        $fields[8] = ($parent_count > 2) ? $parents[$parent_count - 3]->name : '';

        $sql2 = "SELECT fid FROM {uc_product_fees} WHERE nid ='%d'";
        $q2 = db_query($sql2, $r['nid']);
        //print '**'.$r['nid'].'**';
        //print_r($q2);

        if (!db_result($q2)) {


            $product_fees = array();
            foreach ($fees as $fee) {
                $product_fees[] = $fee;
            }echo 'sd';
            //print_r($fields[9]);exit;
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                //put in AU prices
                $fields[9] = $r['sell_price'];
                foreach ($product_fees as $pf) {
                    $fields[9 + $pf['fid']] = $r['sell_price'] + $r['sell_price'] * (get_fee($pf['fid']) / 100);
                }
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                //put in NZ prices
                $fields[17] = $r['price'];
                foreach ($product_fees as $pf) {
                    $fields[17 + $pf['fid']] = $r['price'] + $r['price'] * (get_fee($pf['fid']) / 100);
                }
            }

        } else {


            $product_fees = array();
            while ($r2 = db_fetch_array($q2)) {
                $product_fees[] = $r2;
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                $fields[9] = $r['sell_price'];
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                $fields[17] = $r['price'];
            }
        }

        //$fields[22] = $r['status'];

        if ($output_file) {
            fputcsv($fp, $fields);
        } else {
            print_r($fields);
        }
    }
    if ($output_file) {
        fclose($fp);

           header('Content-type: application/excel');
           header('Content-Disposition: attachment; filename="'.$fname.'"');
           readfile($fpath.$fname);
    }
    return;
}

function biotweaks_form_submit($form_id, $form_values) {
    $fieldName = 'csv';

    $dir = variable_get('file_directory_path', 'files');
    if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$fieldName])) {
        // attempt to save the uploaded file
        $file = file_save_upload($fieldName, array(), $dir, FILE_EXISTS_REPLACE);

        // set error if file was not uploaded
        if (!$file) {
          form_set_error($fieldName, 'Error uploading file.');
          return;
        } else {
          _process_csv($file);
        }
    } else {
        form_set_error('Can\'t upload file!');
        return;
    }
}

function _process_csv($file) {


    global $DEBUG_BT_PROCESS;
    $DEBUG_BT_PROCESS = false;

    //set to just test a single product
    global $CHECK_ONE;
    $CHECK_ONE = true;

    if (0) {
    //delete all products
        $sql = "select nid from node where type = 'product'"; 

        $r = db_query($sql);
        while ($ra = db_fetch_array($r)) {


        }

        print 'all products deleted.';
    }

    //set all products to unpublished
    if (!$DEBUG_BT_PROCESS) {

        if (!$CHECK_ONE) {
            $sql = "update node set status='0' where type='product'";

            db_query($sql);

        }
    }   

    function _fix_currency($str) {
        if ($str == "FREE") {
            return "0";
        } else {
            $ret = str_replace('$', '', $str);
            $ret = str_replace(',', '', $ret);
            return $ret;
        }
    }

    function _get_title($fields) {
        $description = $fields[1];
        $size = $fields[2];

        if (!empty($size)) {
            $ptitle = $description . " - ".$size;
        } else {
            $ptitle = $description;
        }   
        $ptitle = str_replace("*NEW", "", $ptitle);
        $ptitle = str_replace("  ", " ", $ptitle);
        $ptitle = str_replace("  ", " ", $ptitle);
        return $ptitle;
    }

    function _update_product_node($nid, $fields) {
        $sku = $fields[0];
        $description = $fields[1];
        $size = $fields[2];
        $pallet_qty = $fields[3];
        $dg_class = $fields[4];

        $ptitle = _get_title($fields);
        $node = node_load($nid);

        $node->title = $ptitle;
        $node->status = 1;
        $node->model = $sku;
        $node->shippable = 1;
        $node->default_qty = 1;

        $tid = $fields[5];
        $term = taxonomy_get_term($tid);


        if (!$term) {
            drupal_set_message('No category id?');

            return;
        }
        $node->taxonomy[$tid] = $term;
        if ($fields[9]) {

            $node->sell_price = _fix_currency($fields[9]);
        }
        if ($fields[17]) {

            $r = db_fetch_array(db_query("SELECT vid, nid FROM {uc_products} WHERE model = '%s'", $sku));

            $case_price = _fix_currency($fields[17]);                   

            $nz_rid = 6;

            db_query("DELETE FROM uc_price_per_role_prices WHERE nid = %d", $r['nid']);

            db_query("INSERT INTO uc_price_per_role_prices (vid, nid, rid, price) VALUES (%d, %d, %d, '%f')", $r['vid'], $r['nid'], $nz_rid, $case_price);

            $node->role_prices[$nz_rid] = $case_price;
        } else {
            $r = db_fetch_array(db_query("SELECT vid, nid FROM {uc_products} WHERE model = '%s'", $sku));
            $nz_rid = 6;
            db_query("DELETE FROM uc_price_per_role_prices WHERE nid = %d", $r['nid']);
            if (isset($node->role_prices[$nz_rid])) {
                unset($node->role_prices[$nz_rid]);
            }
        }

        if ($fields[9] && !$fields[17]) {

            $settings = BIOTWEAKS_AU_ONLY_SETTINGS;

            db_query("delete from content_access where nid = '".$r['nid']."'");
            db_query("insert into content_access (settings, nid) values ('%s', %d)",$settings, $r['nid']);
        } else if ($fields[17] && !$fields[9]) {


            $settings = BIOTWEAKS_NZ_ONLY_SETTINGS;

            db_query("delete from content_access where nid = '".$r['nid']."'");
            db_query("insert into content_access (settings, nid) values ('%s', %d)",$settings, $r['nid']);
        } else {

            db_query("delete from content_access where nid = '%d'", $r['nid']);
        }

        db_query("delete from {uc_product_fees} where nid = '%d'", $nid);


        if (!function_exists('_exclude_discount')) {
            function _exclude_discount($fid, $nid) {


                db_query("delete from uc_product_fees where nid = '%d' and fid = '%d'", $nid, $fid);
                db_query("INSERT INTO {uc_product_fees} (nid, fid, price, is_active) VALUES (%d, %d, '0', '0')", $nid, $fid);
            }
        }

        for ($i = 0; $i<7; $i++) {

            if ($fields[9]) {

                if (!$fields[10 + $i]) {

                    _exclude_discount(1 + $i, $nid);
                }
            } else if ($fields[17]) {

                if (!$fields[18 + $i]) {
                    _exclude_discount(1 + $i, $nid);
                }
            }
        }

        if ($fields[26]) {

            $image_directory = $fields[25] ? $fields[25]."/" : "";
            $filepath = $_SERVER['DOCUMENT_ROOT'].'/sites/default/files/'.$image_directory.$fields[26];

            if (file_exists($filepath)) {

                $field = field_file_save_file($filepath, array(), file_directory_path());
                $node->field_image_cache = array(0 => $field);
            }
        }

$n= db_query("select nid from prod_node_relation where nid=".$sku);

$y = db_fetch_object($n);
if($y->nid)
{
db_query("update node set type='product' where nid=".$y->nid);
db_query("update term_node set tid=".$term." where =".$y->nid);
}
else
{

    node_save($node);
}

db_query("INSERT INTO prod_node_relation (nid, sku) VALUES (%d, %d)", $node->nid, $sku);
    }

    $file_name = $file->filepath;
    $fd = fopen ($file_name, "r");

    drupal_set_message('Importing products');

    $fields = fgetcsv($fd, 4096, ",");
    $count = 0;

    while (($fields = fgetcsv($fd, 4096, ",")) !== FALSE) {

        $sku = $fields[0];


        $sql = "select nid from uc_products where model = '%s'";
        $q = db_query($sql, $sku);
        $r = db_fetch_array($q);

        if ($r) {

            _update_product_node($r['nid'], $fields);
            drupal_set_message('Updated product: '.$sku);

        } else {
            $sql2 = "select nid from node where title = '%s'";
            $q2 = db_query($sql2, $fields[1]);
            $r2 = db_fetch_array($q2);

            if ($r2) {
                _update_product_node($r['nid'], $fields);
                drupal_set_message('Updated product: '.$fields[1]);
            } else {

                drupal_set_message('Create product: '.$sku);
                if ($fields[0]) {

                    if ($DEBUG_BT_PROCESS) {
                        drupal_set_message('Need to create product:'.$fields[0]);
                    } else {
                        $node = (object)array(
                            'uid'=>1,
                            'name'=> 'admin',
                            'type'=> 'product',
                            'title'=> _get_title($fields)   );
                        $contenttype = content_types('product');
                        foreach ($contenttype['fields'] as $fieldname => $field) {
                            if(isset($field['widget']['default_value'])) {
                                $node->$fieldname = $field['widget']['default_value'];
                            }
                        }

                        node_save($node);

                        $nid = $node->nid;

                        _update_product_node($nid, $fields);
                        drupal_set_message('Created and updated product: '.$sku);
                    }
                } else {

                }
            }
        }
        break;
        $count++;
    }
    drupal_set_message('Finished importing.');  


}

This is how it is being visible now when I open CSV file

This is how it is being visible no when I open CSV file

This is frontend

enter image description here

  • Can you paste any notices and error which you've in your watchdog during the download? E.g. drush watchdog-show --tail . Do you've the right permissions? Is biotweaks_product_csv_download() your main function to perform that action? – kenorb Mar 23 '15 at 10:29
  • Yes i perform that action through biotweaks_product_csv_download() ,i sort out the issue in query section it's works fine now.Thanks – Parvateesam Mar 24 '15 at 7:11
1

Need to replace below code in place of same action in old code ,it's working fine in our end.

function biotweaks_product_csv_download() {

    $fpath = '/home/biolab/public_html/';
    $fname = 'products.csv';

    $output_file = true;

    if ($output_file) {
        $fp = fopen($fpath.$fname, 'w');
    }



    $header = array('Product Code', 'Product Description', 'Size', 'Pallet Qty', 'DG Class', 'Category ID', 'Category Name', 'Subcategory Name', 'Subsubcategory Name', 'AU Case Price (ex. GST)', 'AU Price List 21', 'AU Price List 22', 'AU Price List 23', 'AU Price List 24', 'AU Price List 25', 'AU Price List 26', 'AU Price List 27', 'NZ Case Price (ex. GST)', 'NZ Price List 21', 'NZ Price List 22', 'NZ Price List 23', 'NZ Price List 24', 'NZ Price List 25', 'NZ Price List 26', 'NZ Price List 27', 'Image directory', 'Image filename');


    if ($output_file) {
        fputcsv($fp, $header);
    }

    $q = db_query('SELECT fid, price from {uc_fees}');
    global $fees;
    $fees = array();
    while ($r = db_fetch_array($q)) {
        $fees[] = $r;
    }

    function get_fee($fid) {
        global $fees;
        foreach ($fees as $fee) {
            if ($fid == $fee['fid']) {
                return $fee['price'];
            }
        }
        return 0;
    }

    $sql = "SELECT  n.status, n.nid,  n.title, tn.tid, ucp.model, ucp.sell_price,  upp.price,  ca.settings FROM  {uc_products} as ucp,  {term_node} as tn,  {node} as n left join {uc_price_per_role_prices} as upp on n.nid = upp.nid left join {content_access} as ca on n.nid = ca.nid   WHERE  ucp.nid = n.nid and  n.nid = tn.nid  AND n.status = 1 ORDER BY tn.tid";

    $q = db_query($sql);


    while ($r = db_fetch_array($q)) {


        $parents = taxonomy_get_parents_all($r['tid']);
        $parent_count = count($parents);

        $fields = array();
        for ($i = 0; $i<26; $i++) {
            $fields[] = '';
        }
        $fields[0] = $r['model'];
        $fields[1] = $r['title'];
        $fields[5] = $r['tid'];
        $fields[6] = $parents[$parent_count-1]->name;
        $fields[7] = ($parent_count > 1) ? $parents[$parent_count - 2]->name : '';
        $fields[8] = ($parent_count > 2) ? $parents[$parent_count - 3]->name : '';

        $sql2 = "SELECT fid FROM {uc_product_fees} WHERE nid ='%d'";
        $q2 = db_query($sql2, $r['nid']);


        if (!db_result($q2)) {


            $product_fees = array();
            foreach ($fees as $fee) {
                $product_fees[] = $fee;
            }


            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {

                $fields[9] = $r['sell_price'];
                foreach ($product_fees as $pf) {
                    $fields[9 + $pf['fid']] = $r['sell_price'] + $r['sell_price'] * (get_fee($pf['fid']) / 100);
                }
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {

                $fields[17] = $r['price'];
                foreach ($product_fees as $pf) {
                    $fields[17 + $pf['fid']] = $r['price'] + $r['price'] * (get_fee($pf['fid']) / 100);
                }
            }

        } else {


            $product_fees = array();
            while ($r2 = db_fetch_array($q2)) {
                $product_fees[] = $r2;
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_AU_ONLY_SETTINGS) {
                $fields[9] = $r['sell_price'];
            }
            if (empty($r['settings']) || $r['settings'] == BIOTWEAKS_NZ_ONLY_SETTINGS) {
                $fields[17] = $r['price'];
            }
        }



        if ($output_file) {
            fputcsv($fp, $fields);
        } else {
            print_r($fields);
        }
    }
    if ($output_file) {
        fclose($fp);

           header('Content-type: application/excel');
           header('Content-Disposition: attachment; filename="'.$fname.'"');
           readfile($fpath.$fname);
    }
    return;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.