Date fields entered with value 0000-00-00

1

I am not able to save the dates of a form in my DB, the variables are correct, since I can view them before sending them to the database, but when sending to DB it goes in the format 0000-00-00 , this is zeroed . The code I have is this:

// NESSE MOMENTO USO UMA FUNÇÃO PARA ALTERAR A DATA PARA 0000-00-00
require_once("../_comp/internos/funcoes.php");

// FORMATANDO CAMPOS PARA INSERÇÃO
$Data = parseDate($_POST["dData"], "Y-m-d");
$DataFinalPrevista = parseDate($_POST["dDataFinalPrevista"], "Y-m-d");
$DataInicioVigencia = parseDate($_POST["dDataInicioVigencia"], "Y-m-d");
$DataTerminoVigencia = parseDate($_POST["dDataTerminoVigencia"], "Y-m-d");

// FORMATANDO CAMPO PARA GRAVAR PADRÃO MYSQL
$fValor = $_POST['fValor'];
$Valor = str_replace(',','.',str_replace('.','',$fValor));

// REGISTRO DO LOG
$dataAgora = date('d/m/Y');
$hora = date("H:i:s"); 
$partes = explode("/", $dataAgora);
$dia = $partes[0];
$mes = $partes[1];
$ano = $partes[2];

// CONFIGURANDO ESTADO 
$Estado = 1;

// COMPONDO O LOG
$Log = $_SESSION['u_login']."_".$dia.$mes.$ano."_".$hora;

$sql = "INSERT INTO gerContrato ( Nome, Descricao, Pessoa, Data, Hora, Estado, IdCategoria, UsrResponsavel, Departamento, Arquivo, LocalNoArquivo, DataFinalPrevista, IdContratoOrigem, SolicitacaoCompra, IdGrupoContrato, InicioVigencia, TerminoVigencia, Valor, Renovacao, PeriodoRenovacao, Tags, Log ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

// Preparar os dados: s = string / i = inteiro / d = decimal / b = blob
if($stmt = $conn->prepare($sql) ){

    $stmt->bind_param(
        "sssdsssssssdsssdddssss",

    // RESGATE DAS VARIÁVEIS        
    $_POST["dNome"],
    $_POST["dDescricao"],
    $_POST["dPessoa"],              
    $Data,
    $_POST["dHora"],
    $Estado,
    $_POST["dCategoria"],
    $_POST["dUsuarioResponsavel"],
    $_POST["dDepartamento"],
    $_POST["dArquivo"],
    $_POST["dLocalArquivo"],
    $DataFinalPrevista,
    $_POST["dContratoOrigem"],
    $_POST["dSolicitacaoCompra"],   
    $_POST["dGrupoContrato"],       
    $DataInicioVigencia ,
    $DataTerminoVigencia,                                                           
    $Valor,
    $_POST["dRenovacao"],
    $_POST["dPeriodoRenovacao"],
    $_POST["dTags"],
    $Log        
    );      

    // DESLIGA O AUTO COMMIT
    // $conn->autocommit(false);

    // INSERINDO REGISTRO NO BD
    if ($stmt->execute()) { 
        $aretorno["msg"] = "Registro inserido com sucesso." . $Data;
    } else {
        $aretorno["msg"] = "Ocorreu um erro na inclusão dos dados:". $stmt->error ." Verifique";
        $aretorno["status"] = "ERRO";
    }

} else {
    $aretorno["msg"] = "Ocorreu um erro na preparação dos dados: "  . $stmt->error . ". Verifique.";
    $aretorno["status"] = "ERRO";
}

// Fecha conexão com o BD
$conn->close();

//retornando o status / mensagem da execução
header('Content-Type: application/json');
echo json_encode($aretorno);

ParseData Code

function parseDate($date, $outputFormat = 'd/m/Y'){
    $formats = array(
        'd/m/Y',
        'd/m/Y H',
        'd/m/Y H:i',
        'd/m/Y H:i:s',
        'Y-m-d',
        'Y-m-d H',
        'Y-m-d H:i',
        'Y-m-d H:i:s',
    );

    foreach($formats as $format){
        $dateObj = DateTime::createFromFormat($format, $date);
        if($dateObj !== false){
            break;
        }
    }

    if($dateObj === false){
        throw new Exception('Data invalida:' . $date);
    }

    return $dateObj->format($outputFormat);
}


function funserialize($serialized, &$into) {
    static $sfalse;
    if ($sfalse === null)
        $sfalse = serialize(false);
    $into = @unserialize($serialized);
    return $into !== false || rtrim($serialized) === $sfalse; //whitespace at end of serialized var is ignored by PHP
}

All fields except dates are being written correctly.

    
asked by anonymous 17.07.2015 / 14:37

2 answers

3

The date is sent blank because it is invalid, the problem is when it is time to bind types, d is for double and not date , change all date fields to s

See the error with the first four fields:

INSERT INTO gerContrato ( Nome, Descricao, Pessoa, Data) ...
                  |--------^   
                  ||---------------^
                  |||------------------------^
                  ||||------------------------------^ 
                  ||||   
stmt->bind_param("sssd", ...
    
17.07.2015 / 15:30
1

You have already checked the database if the [Date] field is set to receive ["Ymd"], in most cases the dates are set to ["YYYY-MM-DD"] and include hours ["YYYY -MM-DD HH: MM: SS "], if you are switching to a variable in the correct format you will have no problems. Check the configuration of the field in the table, and what is passing in the parameter.

    
17.07.2015 / 14:52