无法将日期时间从csv插入到mysql中

时间:2014-08-30 14:42:39

标签: php mysql datetime csv sql-insert

我正在努力获得一个" datetime"从csv文件中将其插入MySql数据库。我究竟做错了什么?提前谢谢!

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
            {
                $date = new Datetime();
                $this->date->format('Y-d-m H:i:s', ($data[3]));

                $sql = "INSERT INTO logs(ID, User, Flag, Date) values('$data[0]', '$data[1]', '$data[2]', '$data[3]')";
                $insert = $this->dataBase->getData($sql);

3 个答案:

答案 0 :(得分:0)

$date$this->date不同,这就是您收到错误的原因:

Notice: Undefined property: Import::$date Fatal error: Call to a member function format() on a non-object

答案 1 :(得分:0)

首先,你必须得到数据格式的价值,格式必须是Y- m -d而不是Y-d-

$date = new Datetime($data[3]); 
$myDate = $date->format('Y-m-d H:i:s');

$sql = "INSERT INTO logs(ID, User, Flag, Date) values('$data[0]', '$data[1]', '$data[2]', '$myDate')"; 
$insert = $this->dataBase->getData($sql);

答案 2 :(得分:0)

MySQL为您处理date formatting

 INSERT INTO logs(ID, User, Flag, Date) values('$data[0]', '$data[1]', '$data[2]', DATE_FORMAT('$myDate', '%d %b %Y %T:%f'));";

您可能还想查看PDO和预处理语句,以避免SQL注入。