4

我有以下 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. 你能帮我解决这个问题吗?

4

3 回答 3

13

对日期使用正确的 MYSQL 格式YYYY-MM-DD。例如在你的代码中改变这个:

$data = array(
    'Title' => $title,
    'Description' => $description,
    'When' => date('Y-m-d', strtotime($when)),
    'Duration' => $duration,
    'Where' => $where
);
于 2013-02-13T08:29:44.597 回答
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
);
于 2013-02-13T08:28:44.953 回答
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
);
于 2019-05-29T08:52:08.333 回答