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

后端 未结 11 910
傲寒
傲寒 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:56

    This is the easy way to handle timestamp insertion

    $data = array('created_on' => date('Y-m-d H:i:s'));
    
    0 讨论(0)
  • 2020-12-01 02:57

    $this->db->query("update table_name set ts = now() where 1=1") also works for current time stamp!

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-12-01 03:00
        $data = array(
                'name' => $name ,
                'email' => $email,
                'time' =>date('Y-m-d H:i:s')
                );
                $this->db->insert('mytable', $data);
    
    0 讨论(0)
  • 2020-12-01 03:02

    putting NOW() in quotes won't work as Active Records will put escape the NOW() into a string and tries to push it into the db as a string of "NOW()"... you will need to use

    $this->db->set('time', 'NOW()', FALSE); 
    

    to set it correctly.

    you can always check your sql afterward with

    $this->db->last_query();
    
    0 讨论(0)
  • 2020-12-01 03:06

    I typically use triggers to handle timestamps but I think this may work.

    $data = array(
        'name' => $name,
        'email' => $email
    );
    
    $this->db->set('time', 'NOW()', FALSE);
    $this->db->insert('mytable', $data);
    
    0 讨论(0)
提交回复
热议问题