【问题标题】:String datetime insert into mysql database with codeigniter使用codeigniter将字符串日期时间插入mysql数据库
【发布时间】:2013-01-28 17:57:33
【问题描述】:

我有以下 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 之外的所有内容都正确插入。你能帮我解决这个问题吗?

【问题讨论】:

    标签: php mysql codeigniter datetime


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      mySQL 中的日期是YYYY-MM-DD

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

      所以试试这个:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-04-27
          • 1970-01-01
          • 2019-10-06
          • 2011-02-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多