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(
This is the easy way to handle timestamp insertion
$data = array('created_on' => date('Y-m-d H:i:s'));
$this->db->query("update table_name set ts = now() where 1=1")
also works for current time stamp!
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');
$data = array(
'name' => $name ,
'email' => $email,
'time' =>date('Y-m-d H:i:s')
);
$this->db->insert('mytable', $data);
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();
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);