Send null date if not filled in

Asked

Viewed 1,654 times

0

How do I enter a date null in that capacity?

    $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 mandatory and if the user does not put anything on form, it saves a date like 0000-00-00.

  • Is the field type in DBMS date and configured to allow nulls? Problems of this type are more related to the way the query inserts a null value.

  • Yes, date and null

1 answer

2


You need to concatenate the quotes (') with the date, so that in the 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);";

Thus, the possible outputs of the variable $sql would be:

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

or

INSERT tabela (campo_data) VALUES (NULL);
  • He entered inside Else, but still does not play NULL, I tested putting a value type 2017-02-02 and he returned this value, but when I put the "NULL" he keeps returning 0000-00-00

  • Keeping our friend’s code above I’ll leave an example of a table that saves date as null. CREATE TABLE seubd.new_table ( ID INT NOT NULL AUTO_INCREMENT, data_insercao DATE NULL DEFAULT NULL, nome VARCHAR(45) NOT NULL, PRIMARY KEY (ID)); the big secret there is in the setting in the default value of the column 'DEFAULT NULL'. abs.

Browser other questions tagged

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