字符串datetime使用codeigniter插入到mysql数据库中

时间:2013-02-13 08:27:40

标签: php mysql codeigniter datetime

我正在关注MySQL表

EventId     ObjectKey   Title           Description     When        Duration        Where           Status
INT         CHAR(36)    VARCHAR(500)    VARCHAR(8000)   DATETIME    VARCHAR(500)    VARCHAR(500)    TINYINT

我的PHP数组是

$data = array(
    'Title' => $title,
    'Description' => $description,
    'When' => $when,
    'Duration' => $duration,
    'Where' => $where
);

变量$when包含02/21/2013。当我尝试使用CodeIgniter插入表时

public function insert_event($guid, $data)
{
    $CI = & get_instance();
    $CI->load->database('default');
    $CI->db->set($data);
    $CI->db->set('ObjectKey', $guid);
    $CI->db->set('Status', 1);
    $vari = $CI->db->insert('Events');
    return $vari;
}

date外,所有内容都已正确插入。你能帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:13)

使用正确的MYSQL格式作为日期YYYY-MM-DD。例如,在您的代码中更改此内容:

$data = array(
    'Title' => $title,
    'Description' => $description,
    'When' => date('Y-m-d', strtotime($when)),
    'Duration' => $duration,
    'Where' => $where
);

答案 1 :(得分:4)

mySQL中的日期为YYYY-MM-DD

您正在插入日期MM/DD/YYYY

所以试试这个:

$data = array(
    'Title' => $title,
    'Description' => $description,
    'When' => date('Y-m-d', strtotime($when)),
    'Duration' => $duration,
    'Where' => $where
);

答案 2 :(得分:1)

在mysql中以任何格式存储字符串日期的最简单方法

$srcFormat = "m/d/Y"; //convert string to php date
$destFormat = "Y-m-d" //convert php date to mysql date string

$data = array(
  'Title' => $title,
  'Description' => $description,
  'When' => DateTime::createFromFormat($srcFormat, $when)->format($destFormat),
  'Duration' => $duration,
  'Where' => $where
);