CodeIgniter:使用时间戳在MySQL中插入一行

时间:2013-10-20 06:59:10

标签: codeigniter codeigniter-2

在CodeIgniter中,我想在包含“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);

如果我使用"NOW()",它只会输入字符串,而不是实际让MySQL使用其NOW关键字。

2 个答案:

答案 0 :(得分:1)

为了在CodeIgniter中使用NOW()函数,您需要使用“set”函数

$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);

答案 1 :(得分:0)

如果您需要了解时区,我建议您以UTC格式存储日期时间 这样:

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

当您检索信息时,您必须使用包含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');