jason white
jason white

Reputation: 711

PHP time() function and MySQL fields

If I use the PHP's Time() function and in MySQL there are 4 fields DATE, DATETIME, TIMESTAMP, and TIME, which one I should use?

In PHP I use the Time() to record both the Date and the time like 5/10/2012, and the time is used to calculate the time elapsed.

Upvotes: 0

Views: 1514

Answers (3)

VettelS
VettelS

Reputation: 1224

The Unix timestamp is the most basic form of a time/date- a "raw format", if you will. Once you have a timestamp, you can get to any other format you want. Personally I don't see the point in storing DATEs or DATETIMEs, only to convert it to a timestamp when you retrieve the data again, which of course you will need to do if you want to display a date/time in any readable format (see date() function).

MySQL has a field time that store the current timestamp when a record is created. Alternatively, and if you want more flexibility, PHP's time() function returns the current timestamp. PHP also has functions for calculating the timestamp at a certain point in time (e.g. if you want to specify a date in dd/mm/yyyy format).

So in summary, I would always use timestamps, and I recommend you do too, unless you have very specific needs.

Upvotes: 1

Roman Newaza
Roman Newaza

Reputation: 11700

I would suggest you to use MySQL Data And Time functions instead. If you need to store current time, use NOW(). It's DATETIME type. Alternatively, you can use Unix Timestamp storing it as INT.

Upvotes: 1

Míla Mrvík
Míla Mrvík

Reputation: 535

Use what you need:

DATE: stores only days ex: 2012-06-11

DATETIME: stores days and time ex: 2012-06-11 12:49:31

TIMESTAMP: stores days and time ex: 2012-06-11 12:49:31 MySQL has function that sets this field to current timestamp, when there was update in the row. Maybe (don't know right now) can be specified by number. Others must be specified 'yyyy-mm-d hh:mm:ss'

to convert DB value to PHP's time use strtotime()

Upvotes: 1

Related Questions