Cepheus
Cepheus

Reputation: 4903

Why is fgetcsv skipping the first row?

I'm using the php function fgetcsv() to read from a csv file. The structure of the csv file is such that, the very first row contains the data I want to import as opposed to the column title. I'd like to import from the very first row but I'm noticing that the first row is being ignored.

If I leave the first row empty, the same behavior persists. It is only when I add some dummy data in the first row's cells that the second row which contains the data I want to be imported actually gets imported and all other rows after that are imported as would be expected.

<?php
$handle = fopen($_FILES['materials']['tmp_name'], "r");
$data = fgetcsv($handle, 1000, ",");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if($this->checkMaterialsDuplicate($data[3]) != false) {
        Session::setSession('import_failure', 'The Materials for TX '.
            $this->_tx_no.' have already been added.');
        Helper::redirect('?section=store&subsection=import_design&page=import_design');
    }
    echo "<pre>";print_r($data);echo "</pre>";exit;
    $this->_fields[] = 'implicit_qty_of_fittings';
    $this->_values[] = $this->db->escape($data[1]);

    $this->_fields[] = 'qty_of_desired_materials';
    $this->_values[] = $this->db->escape($data[2]);

    $this->_fields[] = 'tx_no';
    $this->_values[] = $this->db->escape($data[3]);

    $this->_fields[] = 'contractor_name';
    $this->_values[] = $this->db->escape($data[4]);

    $this->_fields[] = 'contractor_id';
    $this->_values[] = $this->db->escape($data[5]);

    $this->_fields[] = 'issue_date';
    $this->_values[] = $this->db->escape($data[6]);

    $this->_fields[] = 'due_date';
    $this->_values[] = $this->db->escape($data[7]);

    $this->_fields[] = 'fitting_id';
    $this->_values[] = $this->db->escape($data[8]);

    $this->_fields[] = 'qty_multiplied_fittings';
    $this->_values[] = $this->db->escape($data[9]);

    $this->_fields[] = 'imported';
    $this->_values[] = 1;

    $sql  = "INSERT INTO `{$this->_table_6}` (`";
    $sql .= implode("`, `", $this->_fields);
    $sql .= "`) VALUES ('";
    $sql .= implode("', '", $this->_values);
    $sql .= "')";

    if (!$this->db->query($sql)) {
        $error[] = $sql;
    }

    $this->_subcontractor_name = $data[4];
    $this->_subcontractor_id = $data[5];
    unset($this->_fields);
    unset($this->_values);
}

Link to sample csv here

Upvotes: 2

Views: 3539

Answers (1)

iainn
iainn

Reputation: 17417

You've got an extra call to fgetcsv() before the loop begins - this will be fetching the first row and then discarding it, which means the loop will start on the second row.

Just remove this line and it should work correctly

$data = fgetcsv($handle, 1000, ",");

Upvotes: 8

Related Questions