Set field to null - Codeigniter

Asked

Viewed 372 times

1

Hello, beauty?

I’m making a update in a table and I am sending the data array. However, I have a date field. Every time I update, it sends the field as 'dtnascimento' = ''. When this data arrives in the database, my database arrow the date as 0000-00-00.

What I wish to do: make a check if my the position of my array is null. If null, set the value to arrive in the database as (NULL).

Below my current code:

function atualizarFuncionario($dados){

    if ($dados['dtnascimento'] === '') {
        $dados['dtnascimento'] = NULL;
    }

    $where = array(
     'idfuncionario'    => $dados['idfuncionario'],
     'idempresa'        => $dados['idempresa']
    );
    $this->db->update($this->tabela,html_escape($dados),$where);

}

If anyone knows, a moral there rs

  • Failed to check if null or pass value null to the bank?

  • @rray already tried it and it happens the same thing that I quoted in the second line, 'dtnascimento' = ''.

  • I did some tests with the PDO, recorded null when I passed null or 'null', blank turned out to be like 0000-00-00

  • Changes the field data for date NULL format, and when you add, pass the field as 'NULL' as well

2 answers

1

Dude, why don’t you arrow in Active Record which fields you want to update?

Particularly I prefer to update only the specific data:

Assuming you will update only the name (which is filled in) and the date field, which you do not know is filled in...

$this->db-trans_begin();
$this->db->set('Nome', $dados['Nome']);
if($dados['dtnascimento'] != ''){
   $this->db->set('Data', $dados['dtnascimento']);
}
$this->db->where('idfuncionario', $dados['idfuncionario']);
$this->db->where('idempresa', $dados['idempresa']);
$this->db->update('tabela');
if($this->db->trans_status() === true){
   $this->db->trans_commit();
}else{
   $this->db->trans_rollback();
}

Thus, if the date field is not filled in, it changes nothing... I hope I helped. Oss!

0

Usually I wear the unset()

function atualizarFuncionario($dados){

    if ($dados['dtnascimento'] === '') {
        unset($dados['dtnascimento']);
    }

    $where = array(
     'idfuncionario'    => $dados['idfuncionario'],
     'idempresa'        => $dados['idempresa']
    );
    $this->db->update($this->tabela,html_escape($dados),$where);

}
  • 1

    That ain’t gonna kill the key?

  • The truth is that I want to update the field, but to null. Got it? That way, you will not update it in the database. That way you’ll leave the old value if you leave the field as null.

  • Hmm got it! Tried using $var = 'NULL'

  • I tried yes, it gave the same thing I talked to @rray up there. Only he arrow 'dtnascimento' = 'NULL' and when I go look in the bank is 0000-00-00.

  • 1

    I think it is your database configuration...you are using mysql?

  • Yes, Rafael. I’m using mysql

Show 1 more comment

Browser other questions tagged

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