Error uploading csv file to mysql

0

I have the Index and the php in a single script. I have a button that gives me the option to search the directory for the csv file to upload to the database.

Before selecting the file I get the following error:

  

Notice: Undefined index: excel in   C: \ xampp \ htdocs \ Registry_2 \ process.php on line 30

Then I select the csv file and give it "Upload file" And start loading.

When it finishes I get the following errors:

  

Notice: Undefined offset: 1 in C: \ xampp \ htdocs \ Registry_2 \ process.php   online 86

     

Notice: Undefined offset: 5 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 88

     

Notice: Undefined offset: 3 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 89

     

Notice: Undefined index: in C: \ xampp \ htdocs \ Registry_2 \ process.php on line 89

     

Notice: Undefined offset: 1 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 90

     

Notice: Undefined offset: 6 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 92

     

Notice: Undefined offset: 1 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 86

     

Notice: Undefined offset: 5 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 88

     

Notice: Undefined offset: 3 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 89

     

Notice: Undefined index: in C: \ xampp \ htdocs \ Registry_2 \ process.php on line 89

     

Notice: Undefined offset: 1 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 90

     

Notice: Undefined offset: 6 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 92

     

Notice: Undefined offset: 1 in C: \ xampp \ htdocs \ Register_2 \ process.php on line 86

And so for the number of rows and columns that the CSV file has.

What is my question?

If the CSV file has, for example, 100 files Why upload the 100 files (or whatever number) to the database WITHOUT ANY ERROR OR LOSS OF DATA but I see that error or news? p>

THIS IS THE CODE

 < script type="text/javascript" >

$(function(){
        $("#btnEnviar").click(function(){
            $("#cuerpoPagina").load('procesar.php',$("#frmAsignar").serialize());
        })
    });
        function subirArchivoExcel()
            {
            if (document.frmSubirArchivo.excel.value == "") 
                {
                alert("¡Error!. ¡Debe subir un archivo!");
                document.frmSubirArchivo.excel.focus();
                return false;
                }

            document.frmSubirArchivo.action="procesar.php";
            document.frmSubirArchivo.submit();
            }
    </ script >
<?php

echo '  <form name="frmSubirArchivo" action"procesar.php" method="post" enctype="multipart/form-data">
            <p >Archivo excel</ p>
            <p ><input type="file" name="excel" /></ p>
            <p ><input type="button" name="btnEnviar" id="btnEnviar" value="Subir Archivo" onclick="subirArchivoExcel();" ></ p>
        </form>';

include 'Conexion.php';

if (substr($_FILES['excel']['name'],-3)=="csv") 
    {
    $fecha      = date('Y-m-d');
    $hora       = time("HH:MM:SS");
    $carpeta    = "Ejemplo/";
    $carpeta    = "";
    $excel      = $fecha."-".$hora."-".$_FILES['excel']['name'];

    move_uploaded_file($_FILES['excel']['tmp_name'], "$carpeta$excel");

    //echo "$carpeta$excel";

    //print_r($_FILES);

    $contador = 0;
    $row      = 1;

    $fp = fopen("$carpeta$excel", "r");

    $meses = array( 'ENERO'         => '01',
                    'FEBRERO'       => '02',
                    'MARZO'         => '03',
                    'ABRIL'         => '04',
                    'MAYO'          => '05',
                    'JUNIO'         => '06',
                    'JULIO'         => '07',
                    'AGOSTO'        => '08',
                    'SEPTIEMBRE'    => '09',
                    'OCTUBRE'       => '10',
                    'NOVIEMBRE'     => '11',
                    'DICIEMBRE'     => '12');

    //echo $dias;

    //fgetcsv. obtiene los valores que estan en el csv y los extrae

    while ($data = fgetcsv($fp, 1000, ";")) 
        {
        //Si la línea es igual a 5 no guardamos porque serian los títulos de la hoja de excel
        if ($row >= 7) 
            {
            //print_r("<pre>Row: ".$row);
            //print_r($data);
            //print_r("</pre>");

            // TEXTO:   jueves, 01 de junio de 2017 21:38
            $laFecha = explode(",", $data[1]);

            $fecArchivo = explode(" ", $laFecha[1]);
            //print_r($fecArchivo);
            $anno = $fecArchivo[5];
            $mes  = $meses[strtoupper($fecArchivo[3])];
            $dia  = $fecArchivo[1];

            $hora = $fecArchivo[6];

            $fechaReal = $anno."-".$mes."-".$dia;

            //echo $fechaReal;

            //echo $contador." - ";

            $sql_guardar  = 'INSERT INTO registros  (   Dia,
                                                        Hora,
                                                        Tipo_Acceso,
                                                        Puerta,
                                                        Tipo,
                                                        Tarjeta,
                                                        Nombres,
                                                        Apellidos,
                                                        Documento,
                                                        Empresa)';
            $sql_guardar .=         'VALUES(            "'.$fechaReal.'",
                                                        "'.$hora.'",
                                                        "'.$data[2].'",
                                                        "'.$data[3].'",
                                                        "'.$data[6].'",
                                                        "'.$data[7].'",
                                                        "'.$data[8].'",
                                                        "'.$data[9].'",
                                                        "'.$data[10].'",
                                                        "'.$data[12].'")';

            $contador++;

            //echo "7: ->".$data[7]."<- 10:->".$data[10]."<-";

            if ($data[7] != '') 
                {
                //echo $sql_guardar;

                //print_r("<pre>");
                //  print_r($sql_guardar);
                //print_r("</pre>");

                mysql_query($sql_guardar) or die(mysql_error());

                if (!$sql_guardar)
                    {
                    echo '<div>¡Hubo un problema al momento de importar el archivo! 
                            <br>¡Por favor vuelva a intentarlo!</div>';
                    exit;
                    }
                }
            }

        $row++;

        }

    fclose($fp);
    echo '<div>¡La importación del archivo se subió satisfactoriamente!</div>';
    exit;
    }
?>
    
asked by FOX 09.08.2017 в 17:13
source

1 answer

1

I see two problems in your code:

  • You have to avoid running substr ($ _ FILES ['excel'] ['name'], - 3) == "csv" if a file has not yet been sent.
  • The way you read the file, it may be that in some lines you do not get the field that has a date. With the following code you can check it, in case of not finding a date it will show it:

    <script type="text/javascript" >
    
    $(function(){
        $("#btnEnviar").click(function(){
            $("#cuerpoPagina").load('procesar.php',$("#frmAsignar").serialize());
        })
    });
    
        function subirArchivoExcel()
        {
            if (document.frmSubirArchivo.excel.value == "") 
            {
            alert("¡Error!. ¡Debe subir un archivo!");
            document.frmSubirArchivo.excel.focus();
            return false;
            }
    
            document.frmSubirArchivo.action="procesar.php";
            document.frmSubirArchivo.submit();
        }
    </script>
    <?php
    
    echo '<form name="frmSubirArchivo" action"procesar.php" method="post" enctype="multipart/form-data">
                <p >Archivo excel</ p>
                <p ><input type="file" name="excel" /></ p>
                <p ><input type="button" name="btnEnviar" id="btnEnviar" value="Subir Archivo" onclick="subirArchivoExcel();" ></ p>
        </form>';
    
    include 'Conexion.php';
    
    if (isset($_FILES['excel']) && !empty($_FILES['excel']) && substr($_FILES['excel']['name'],-3)=="csv")
    {
        $fecha      = date('Y-m-d');
        $hora       = time("HH:MM:SS");
        $carpeta    = "Ejemplo/";
        $carpeta    = "";
        $excel      = $fecha."-".$hora."-".$_FILES['excel']['name'];
    
        move_uploaded_file($_FILES['excel']['tmp_name'], "$carpeta$excel");
    
        //echo "$carpeta$excel";
    
        //print_r($_FILES);
    
        $contador = 0;
        $row      = 1;
    
        $fp = fopen("$carpeta$excel", "r");
    
        $meses = array( 'ENERO'         => '01',
                        'FEBRERO'       => '02',
                        'MARZO'         => '03',
                        'ABRIL'         => '04',
                        'MAYO'          => '05',
                        'JUNIO'         => '06',
                        'JULIO'         => '07',
                        'AGOSTO'        => '08',
                        'SEPTIEMBRE'    => '09',
                        'OCTUBRE'       => '10',
                        'NOVIEMBRE'     => '11',
                        'DICIEMBRE'     => '12');
    
        //echo $dias;
    
        //fgetcsv. obtiene los valores que estan en el csv y los extrae
    
        while ($data = fgetcsv($fp, 1000, ";"))
        {
            //Si la línea es igual a 5 no guardamos porque serian los títulos de la hoja de excel
            if ($row >= 7) 
            {
                //print_r("<pre>Row: ".$row);
                //print_r($data);
                //print_r("</pre>");
    
                // TEXTO:   jueves, 01 de junio de 2017 21:38
                $laFecha = explode(",", $data[1]);
    
                if(count($laFecha) == 2)
                {
                    $fecArchivo = explode(" ", $laFecha[1]);
                    //print_r($fecArchivo);
                    $anno = $fecArchivo[5];
                    $mes  = $meses[strtoupper($fecArchivo[3])];
                    $dia  = $fecArchivo[1];
    
                    $hora = $fecArchivo[6];
    
                    $fechaReal = $anno."-".$mes."-".$dia;
    
                    //echo $fechaReal;
    
                    //echo $contador." - ";
    
                    $sql_guardar  = 'INSERT INTO registros  (   Dia,
                                                                Hora,
                                                                Tipo_Acceso,
                                                                Puerta,
                                                                Tipo,
                                                                Tarjeta,
                                                                Nombres,
                                                                Apellidos,
                                                                Documento,
                                                                Empresa)';
                    $sql_guardar .=         'VALUES(            "'.$fechaReal.'",
                                                                "'.$hora.'",
                                                                "'.$data[2].'",
                                                                "'.$data[3].'",
                                                                "'.$data[6].'",
                                                                "'.$data[7].'",
                                                                "'.$data[8].'",
                                                                "'.$data[9].'",
                                                                "'.$data[10].'",
                                                                "'.$data[12].'")';
    
                    $contador++;
    
                    //echo "7: ->".$data[7]."<- 10:->".$data[10]."<-";
    
                    if ($data[7] != '') 
                    {
                        //echo $sql_guardar;
    
                        //print_r("<pre>");
                        //  print_r($sql_guardar);
                        //print_r("</pre>");
    
                        mysql_query($sql_guardar) or die(mysql_error());
    
                        if (!$sql_guardar)
                        {
                        echo '<div>¡Hubo un problema al momento de importar el archivo! 
                                <br>¡Por favor vuelva a intentarlo!</div>';
                        exit;
                        }
                    }
                }
                else
                    echo '<br>No se encontró una fecha válida en el dato: '.$data[1];
    
            }
    
            $row++;
        }
    
        fclose($fp);
        echo '<div>¡La importación del archivo se subió satisfactoriamente!</div>';
        exit;
    }
    ?>
    
  • If you have any problems, let me know.

        
    answered by 10.08.2017 / 00:40
    source