Don P
Don P

Reputation: 63567

CodeIgniter: Insert a row into MySQL with timestamp

In CodeIgniter, I want to insert a row into a db that includes a timestamp for "now".

$message_row = array(
            "sender_email" => $recruiter_email,
            "recipient_email" => $recruiter_email,
            "message" => $recruiter_email,
            "send_date" => "NOW()" // hmmm how do I do this?
        );

$this->db->insert('messages', $message_row);

If I use "NOW()" it will just enter the string, and not actual have MySQL use its NOW keyword.

Upvotes: 0

Views: 3075

Answers (2)

PolloZen
PolloZen

Reputation: 664

In order to use NOW() function in CodeIgniter you need to use "set" function

$table = 'user';    

$message_row = array(
        "sender_email" => $recruiter_email,
        "recipient_email" => $recruiter_email,
        "message" => $recruiter_email
    );

$this->db->set('send_date', 'NOW()', false);

$this->db->insert($table, $message_row);

Upvotes: 1

pgee70
pgee70

Reputation: 3974

if you need to be timezone aware, i recommend you store the datetime in UTC format.
so:

   $now = new DateTime ( NULL, new DateTimeZone('UTC'));
   $message_row = array(
        "sender_email" => $recruiter_email,
        "recipient_email" => $recruiter_email,
        "message" => $recruiter_email,
        "send_date" => $now->format('Y-m-d H:i:s')
    );

when you retrieve the information, you have to know the user's timezone, using a $row that contains the send_date:

$then = new DateTime( $row->send_date, new DateTimeZone('UTC'));
$then->setTimeZone(new DateTimeZone($userstimezone));
echo $then->format('Y-M-D H:i:s');

Upvotes: 0

Related Questions