Time Stamp differences in MySQL and PHP

MySQL and PHP handle time and data data in different ways, and it's important to be aware of the difference.

Both these environments have a TIMESTAMP construct, but they're not entirely compatible.

While PHP uses a UNIX timestamp format (an integer representing the number of seconds since January 1st, 1970) MySQL's TIMESTAMP data type uses a YYYY-MM-DD HH:MM:SS format.

You can overcome this by using the mysql funtion UNIX_TIMESTAMP() to pull dates in the UNIX format native to PHP.

Making this conversion in your SQL query is generally more efficient and simple than converting in PHP.  Remember, you always want to work your data as much as you can in the SQL query and deliver a clean set of data to PHP.

In fact, if you like you can pull the same attribute in different ways in the same query, creating what I'll call pseudo-attributes, as in;

[SOURCECODE language='sql']SELECT UNIX_TIMESTAMP(date_attribute) AS unix_date,date_attribute AS nice_date FROM mytable;[/SOURCECODE]

This gives you two dates to work with in PHP, represented as unix_date and nice_date for a more human readable format, and balances the processing between your web and database servers.

About Editor