82

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(
        'name' => $name ,
        'email' => $email,
        'time' => NOW()
        );
        $this->db->insert('mytable', $data);

This is because CodeIgniter’s ActiveRecord class automatically escapes the input.

The following works fine, by calling set() and passing peratmeter FALSE, so that it doesn't escape the NOW().

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

However, my question is that is there any other way than this? For example, if i can use somehow use by adding everything in the data array only? For example, something like:

$data = array(
            'name' => $name ,
            'email' => $email,
            'time' => NOW(), FALSE
            );
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
Roman
  • 3,764
  • 21
  • 52
  • 71
  • 1
    Out of the track and even scope but do you know you can get NOW() like effect using `strtotime`? For e.g. `echo date("N", strtotime('now'));` will give you today's date, refer to php.net/strtotime and php.net/date – Kumar Jun 16 '11 at 05:09

11 Answers11

81

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);
Bill H
  • 2,069
  • 2
  • 20
  • 29
34

Unless I am greatly mistaken, the answer is, "No, there is no way."

The basic problem in situations like that is the fact that you are calling a MySQL function and you're not actually setting a value. CI escapes values so that you can do a clean insert but it does not test to see if those values happen to be calling functions like aes_encrypt, md5, or (in this case) now(). While in most situations this is wonderful, for those situations raw sql is the only recourse.

On a side, date('Y-m-d'); should work as a PHP version of NOW() for MySQL. (It won't work for all versions of SQL though).

cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • 25
    For simplicity I always set timestamps with date('Y-m-d H:i:s') with different ORMs etc, no need to fight against different implementations. – geekuality Jun 15 '11 at 07:47
  • 2
    Personally, I always use Unix timestamps. I know that 1308124173975 will always be a long (or int, or float, or equivalent) in every language and database. I like not having to care. – cwallenpoole Jun 15 '11 at 07:50
  • 1
    That's a good point. I'm lazy so I like having human readable entries if possible. :) – geekuality Jun 15 '11 at 07:52
  • 1
    @jupaju It's just a different type of laziness. I could remember how PgSQL, MySQL, Oracle, Java, PHP, and Python store dates, or I could just have everything be a gosh-darn number. And you know what? If it's a number, then it instantly translates to AS2, AS3, and JS. And when I need the actual date? Go to Chrome, Ctrl-shift-J and paste String(new Date(/*numeric timestamp*/)) – cwallenpoole Jun 15 '11 at 08:09
  • 4
    I'd like to note that using date('Y-m-d H:i:s') may have an issue where the MySQL server and PHP library are using two different timezones without you being aware. For instance I had a host who had MySQL on GMT (+0h) and PHP was EST (-5h). – bafromca Jan 17 '14 at 08:17
15

aspirinemaga, just replace:

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

for it:

$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);
Bruno Rigolon
  • 439
  • 6
  • 5
  • 2
    I'd like to note that according to the docs, this is the CodeIgniter "recommended way". I'd recommend using MySQL's native NOW() rather than PHP's date('Y-m-d H:i:s') if you're on a shared host as they might be set to different timezones. – bafromca Jan 17 '14 at 08:19
  • Yup, in theory you can't decide design time what your infrastructure will look like 3 years down the road. In reality, I can, often do, but shouldn't. – Herbert Van-Vliet Sep 24 '21 at 22:51
13

This is the easy way to handle timestamp insertion

$data = array('created_on' => date('Y-m-d H:i:s'));
saurabh kamble
  • 1,510
  • 2
  • 25
  • 42
8

you can load the date helper and use the codeigniter interal now() if you want to reference the users GMT time offset

it woulk look somewhat like this

$data = array(
'created_on' => date('Y-m-d H:i:s',now())
);

If you don't use the GTM master settings and let your users set their own offsets there is no advantage over using php's time() function.

Steven
  • 113
  • 1
  • 5
8
    $data = array(
            'name' => $name ,
            'email' => $email,
            'time' =>date('Y-m-d H:i:s')
            );
            $this->db->insert('mytable', $data);
Sandeep Sherpur
  • 2,418
  • 25
  • 27
4

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');
3

Using the date helper worked for me

$this->load->helper('date');

You can find documentation for date_helper here.

$data = array(
  'created' => now(),
  'modified' => now()
);

$this->db->insert('TABLENAME', $data);
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
3

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();
williamli
  • 3,846
  • 1
  • 18
  • 30
0

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

Max
  • 1,528
  • 21
  • 33
0

run query to get now() from mysql i.e select now() as nowinmysql;

then use codeigniter to get this and put in

$data['created_on'] = $row->noinmyssql;
$this->db->insert($data);
khalrd
  • 60
  • 6