EladElrom.com

Deep Dive Into Technology

Dealing with timezone on MySQL database

Sometimes you need to create a fast mysql command to calculate date/times for a specific logic.

MySQL manual has a great article that helps you create your SQL command:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_current-timestamp

For instance, instead of retrieving all results from a database iterate through the results using a server side scripting and than update the database, we can do the same operation in one command using MySQL:

For instance, look at this command:
UPDATE `database`.`table` SET `active` = '0' WHERE `active` = 1 AND `checkin_time` < DATE_SUB(NOW(),INTERVAL 10 SECOND)

That will check the last time a user checked in and set the user is inactive. It's important to make sure that once you update the database with the latest time, you need to either use internet time or set the apache server to the same time zone as the MySQL database.

You can find the timezone in phpinfo. For instance using PHP on localhost using XAMPP you can find the time zone here:
http://eladelrom.com/blog/xampp/ (or print it using PHP on a server)

If timezone is not set correctly, you can set it on php.ini
Look for: Change:

date.timezone = 'EST'

Than you can ensure that the MySQL is running on the same timezone running this command:

SELECT NOW();

Category: MySQL, Tips

Your email address will not be published. Required fields are marked *

*