dongzaotiao2863
2013-02-12 22:17
浏览 67
已采纳

使用PHP存储时间戳:date()或MySQL:FROM_UNIXTIME()?

This may be trivial, but when I want to store a timestamp value (returned by, say, time()) into a TIMESTAMP column in my MySQL table, which of these two are preferable:

function storeTime($timestamp) {
   // Option one:
   $query = "INSERT INTO faketable (datecol) VALUES (FROM_UNIXTIME(".$timestamp."))";
   // Option two:
   $query = "INSERT INTO faketable (datecol) VALUES (".date("YY-MM-DD HH:MM:II", $timestamp).")";
}

Is there even a difference?

EDIT: Sorry, meant date(), not strtotime()...

EDIT 2: NOW() doesn't cut the mustard, the actual timestamp is a paramater sent to my method. I don't know what it is in advance.

EDIT 3: I really shouldn't be asking questions at this time of night. The column in question is, in fact, a TIMESTAMP column, not a DATETIME column.

图片转代码服务由CSDN问答提供 功能建议

这可能很简单,但是当我想存储一个时间戳值时(例如, time返回) ())到我的MySQL表中的 TIMESTAMP 列中,这两个中的哪一个更可取:

  function storeTime($ timestamp)  {
 //选项一:
 $ query =“INSERT INTO faketable(datecol)VALUES(FROM_UNIXTIME(”。$ timestamp。“))”; 
 //选项二:
 $ query =“INSERT INTO faketable  (datecol)VALUES(“。日期(”YY-MM-DD HH:MM:II“,$ timestamp)。”)“; 
} 
   
 
 

是否有差别?

编辑:对不起,意思是 date(),而不是 strtotime() ...

编辑2: NOW()不会切断芥末,实际时间戳是发送给参数的参数 我的方法。 我不知道提前是什么。

编辑3:我真的不应该在这个时候提问。 事实上,有问题的列是 TIMESTAMP 列,而不是 DATETIME 列。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzhuo1958 2013-02-12 22:44
    已采纳

    To answer your question; No there is no logical difference. They both return a string representation of a date https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime, which MySQL will happily convert to a DATETIME, or TIMESTAMP type. As for which is faster evidence would suggest MySQL; http://www.onextrapixel.com/2010/06/23/mysql-has-functions-part-5-php-vs-mysql-performance/, Faster to use MySQL's CURDATE() or PHP's date()?

    打赏 评论
  • doujian1050 2013-02-12 22:20

    Simplest is a FROM_UNIXTIME() in mysql. That'll be a single integer->date conversion. Doing it in PHP means integerr->string->datetime, which is far less efficient.

    As well, your strtotime() is completely invalid. That's not now the function works. You'd end up with's in the database.

    As for storing a "now" timestamp, why not just use a timestamp field type? it automatically sets itself to the current time when you insert/update a record.

    打赏 评论
  • dongxuanyi3406 2013-02-12 22:26

    How bout

    INSERT INTO faketable (datecol) VALUES (UNIX_TIMESTAMP())
    

    I think that's what you're looking for OP

    打赏 评论

相关推荐 更多相似问题