Do not insert date field in my BD

0

I make a massive import module of an excel.csv file but in my date field (DATE) it does not insert the data correctly, it only inserts 0000-00-00, the other fields in the import do it without problem only it's in the date field.

This is an example of a line in the excel.csv file

 7;01/12/2017;15:02:00;;;
 10;26/11/2017;22:37:00;;;

Thanks / Regards

<?php

if (isset($_POST["enviar"])) {//nos permite recepcionar una variable que si exista y que no sea null
    require_once("conexion_excel.php");
    require_once("functions.php");

    $archivo = $_FILES["archivo"]["name"];
    $archivo_copiado= $_FILES["archivo"]["tmp_name"];
    $archivo_guardado = "copia_".$archivo;

    //echo $archivo."esta en la ruta temporal: " .$archivo_copiado;

    if (copy($archivo_copiado ,$archivo_guardado )) {
        //echo "se copeo correctamente el archivo temporal a nuestra carpeta de trabajo <br/>";
    }else{
        //echo "hubo un error <br/>";
    }

    if (file_exists($archivo_guardado)) {

         $fp = fopen($archivo_guardado,"r");//abrir un archivo
         $rows = 0;
         while ($datos = fgetcsv($fp , 1000 , ";")) {
                $rows ++;
               // echo $datos[0] ." ".$datos[1] ." ".$datos[2]." ".$datos[3] ."<br/>";
            if ($rows > 1) {
                $resultado = insertar_datos($datos[0],$datos[1],$datos[2]);
            if($resultado){
                //echo "se inserto los datos correctamente<br/>";
            }else{
                //echo "no se inserto <br/>";
            }
            }
         }



    }else{
        echo "No existe el archivo copiado <br/>";
    }

}


?>
    
asked by Carlos 13.03.2018 в 06:41
source

1 answer

1

The problem

The format to save dates in the database is YYYY-MM-DD , therefore, if your data is given like this: 01/12/2017 is not valid to be inserted in the database.

The solution

It would be necessary to make your data fit to be inserted, and also be correct.

You can do this using the createFromFormat method of the PHP% DateTime class mode:

$csvFecha=$datos[1]; //Columna donde está el dato

/*
  *Esta llamada creará un objeto fecha 
  *formateado así por ejemplo: 2017-12-01
*/

$sqlFecha=DateTime::createFromFormat('d/m/Y', $csvFecha)->format('Y-m-d');
$resultado = insertar_datos($datos[0],$sqlFecha,$datos[2]);

NOTE: Since I see another column with one hour, keep in mind that, if it's the same data, you could save in a single column of type DATETIME , both the date and the hour, precisely for that reason they are called DATETIME , because they serve to keep the date and time.

I hope it serves you.

    
answered by 13.03.2018 в 11:31