Send null date if it is not filled

0

How do I insert a date null into this function?

    $data_saida = $this->post('data_saida');

    //aqui pega a data se não for vazia e formata
    if($data_saida) {
        $arraydata = explode("/", $data_saida);
        $diamontado = $arraydata[2].'-'.$arraydata[1].'-'.$arraydata[0];
        $data_saida = $diamontado;
    }

The problem is that this date is not required and if the user does not put anything in form , it saves a date type 0000-00-00.

    
asked by anonymous 22.08.2017 / 21:43

1 answer

2

You need to concatenate the quotation marks (') with the date, so that else can send null . Here's an example based on your code:

$data_saida = $this->post('data_saida');

//aqui pega a data se não for vazia e formata
if($data_saida) {
    $arraydata = explode("/", $data_saida);
    $diamontado = $arraydata[2].'-'.$arraydata[1].'-'.$arraydata[0];
    $data_saida = "'" . $diamontado . "'";
} else {
    $data_saida = "NULL";
}

$sql = "INSERT tabela (campo_data) VALUES ($data_saida);";

In this way, the possible outputs of the variable $sql would be:

INSERT tabela (campo_data) VALUES ('2017-08-22');

or

INSERT tabela (campo_data) VALUES (NULL);
    
22.08.2017 / 21:51