Duplication of values when importing .csv file when there is one or more column (s) missing in the file

1

When I import a .csv file to save to the database and the file is missing the name of some column instead of inserting null in the database, it repeats the value of the first column.

Here's an example;

$sourcePath = $_FILES['fileTabelaTeste']['tmp_name'];
$targetPath = "/pages/dados/".$_FILES['fileTabelaTeste']['name'];

move_uploaded_file($sourcePath,$targetPath);
$abraArq = fopen("/pages/dados/".$_FILES['fileTabelaTeste']['name']."","r");


    $fieldnames = fgetcsv($abraArq, 5000, ',');

    $idx_prod_codigo = array_search("prod_codigo", $fieldnames);
    $idx_prod_descricao = array_search("prod_descricao", $fieldnames);
    $idx_prod_site = array_search("prod_site", $fieldnames);
    $idx_prod_peso_bruto = array_search("prod_peso_bruto", $fieldnames);
    $idx_und_codigo = array_search("und_codigo", $fieldnames);

    while ($row = fgetcsv($abraArq , 4096, ',')) {
        $prod_codigo = $row[$idx_prod_codigo];
        $prod_descricao = $row[$idx_prod_descricao];
        $prod_site = $row[$idx_prod_site];          
        $prod_peso_bruto = $row[$idx_prod_peso_bruto];
        $prod_peso_bruto = str_replace(",",".",$prod_peso_bruto);
        $und_codigo = $row[$idx_und_codigo];

     $insert = mysql_query("INSERT INTO produtosTeste

                (PROD_CODIGO, PROD_DESCRICAO, PROD_SITE, PROD_PESO_BRUTO, UND_CODIGO) values

                ('$prod_codigo','$prod_descricao','$prod_site','$prod_peso_bruto','$und_codigo') ") or die(mysql_error());
     }

The csv file comes with an input file, and if this file, for example, does not have the column und_codigo, it inserts the same value of prod_codigo in the database.

Within the while after assigning the value to the variable $pro_codigo assigns null to the $row[$idx_prod_codigo] , which was the value that was going to the columns that should save null, and resolved temporarily.     

asked by anonymous 24.05.2018 / 22:37

0 answers