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

使用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.

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

3条回答 默认 最新

  • dongzhuo1958
    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
    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
    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

    点赞 评论

相关推荐