Inserting NOW() into Database with CodeIgniter's Active Record

后端 未结 11 1063
傲寒
傲寒 2020-12-01 02:15

I want to insert current time in database using mySQL function NOW() in Codeigniter\'s active record. The following query won\'t work:

$data = array(
                


        
11条回答
  •  难免孤独
    2020-12-01 02:59

    According to the source code of codeigniter, the function set is defined as:

    public function set($key, $value = '', $escape = TRUE)
    {
        $key = $this->_object_to_array($key);
    
        if ( ! is_array($key))
        {
            $key = array($key => $value);
        }
    
        foreach ($key as $k => $v)
        {
            if ($escape === FALSE)
            {
                $this->ar_set[$this->_protect_identifiers($k)] = $v;
            }
            else
            {
                $this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
            }
        }
    
        return $this;
    }
    

    Apparently, if $key is an array, codeigniter will simply ignore the second parameter $value, but the third parameter $escape will still work throughout the iteration of $key, so in this situation, the following codes work (using the chain method):

    $this->db->set(array(
        'name' => $name ,
        'email' => $email,
        'time' => 'NOW()'), '', FALSE)->insert('mytable');
    

    However, this will unescape all the data, so you can break your data into two parts:

    $this->db->set(array(
        'name' => $name ,
        'email' => $email))->set(array('time' => 'NOW()'), '', FALSE)->insert('mytable');
    

提交回复
热议问题