Date fields entered with value 0000-00-00

Asked

Viewed 1,213 times

1

I’m not able to record the dates of a form in my BD, the variables are correct because I can view them before sending to the bank, but when sending to the BD goes with the format 0000-00-00, this is zero. 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);

Code of Parsedata

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 recorded correctly.

  • 1

    Enter the code of parseDate().

2 answers

3


Date sent blank because invalid problem is time to bind the types, d is for double and not to date, change all date cams to s

See the error with the first four fields:

INSERT INTO gerContrato ( Nome, Descricao, Pessoa, Data) ...
                  |--------^   
                  ||---------------^
                  |||------------------------^
                  ||||------------------------------^ 
                  ||||   
stmt->bind_param("sssd", ...
  • Perfect, thank you so much for the help and excellent tip.

1

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

  • Hello @Luiz Vichiatto, thanks for the tip, everything is normal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.