PHP/MySQL - confusion about storing timestamps - php

I need to store a timestamp for form submissions in a PHP/MySQL form. I would like to be able to query this field with the most flexibility for displaying the data in PHP. What MySQL datatype is best practice, and which PHP function should I use to store/retrieve the data?

I would store this data as TIMESTAMP data type provided by MySQL. This has lots of advantages over other storage options such as DATETIME or INT listed below
It is especially meant to store a particular time instant. No matter which time zone your server is in, and which time zone your mysql client is in, the value of constant CURRENT_TIMESTAMP stored in a TIMESTAMP field will always point to the same instant in the absolute time line.
Internally it uses 4 bytes of space for storage, same as that of an INT data type
It will give you pretty looking, human understandable values in regular queries.
Moreover, these pretty looking values are converted to the timezone of the client connecting to it. This might be good or bad for you. You can always change it to a desired one, including UTC, with set timezone='timezone' if the mysql time zone table is populated or similar to SET time_zone='+5:30'. The latter would work only if there are no daylight saving adjustments in the desired timezone.
Your queries can take the benefit of the fact that MySQL understands this field represents a date. So you could run query like: Get all the registrations happened on month of may for last 3 years.
Use inbuilt functions to change the display format to show unix timestamp or any other valid form.

Use DATETIME or DATE in your database: http://dev.mysql.com/doc/refman/5.6/en/datetime.html
What MySQL datatype is best practice, and which PHP function should I use to store/retrieve the data?
http://ch2.php.net/mysqli

dunno what timestamp you're talking about but for the unix timestamp you'll need INT type field.

Related

Timestamps / Time Zones / PHP / MySQL

I have my Apache server and PHP set to date_default_timezone_set("America/Los_Angeles").
In MySQL I save TIMESTAMP fields with CURRENT_TIMESTAMP and some of them EXTRA as "on update CURRENT_TIMESTAMP".
Am I doing this the right way or am I loosing the whole point of TIMESTAMPS? I want the user to be able to choose their own timezone but it seems like it's saving the local timezone to the MySQL instead of a universal reference point.
Should I instead set the server timezone to UTC and in PHP date_default_timezone_set("America/Los_Angeles") or whatever the user timezone is and then save the values to the MySQL fields with something else than CURRENT_TIMESTAMP (which seems to vary depending on the php setting)?
Thank you!
Ideally you want your database to store data in UTC so that way it's not anchored to any particular geography. Incoming data from users is converted according to the user's time-zone, and anything you display can likewise be converted back to the user's preferred time-zone.
Some systems even go so far as to send UTC time over to the client in the HTML, but tag the element with something that JavaScript hooks on to and re-renders, client-side, with the appropriate local time.
It's best to have a user-specified setting that's persisted in their user record and/or session that defines what conversion, if any, should be done to the dates and times they're specifying or being shown.
It's also worth noting that TIMESTAMP fields are limited to the year 2038, so they're already living on borrowed time. It's best to use a more standard DATETIME field which has a much wider range of acceptable values.

Best way to store date into Mysql for codeigniter application which have different time zone users

I am working on codeigniter application which have users from different time zones. Each user has some notifications based on some dates calculation.
So what should be best way to store date into Mysql? Either timestamp or datetime?
First off, you need to be aware of the locale setting for your mysql server. You want the server to be set to use UTC as a neutral setting. Any data that is stored in the mysql server will be relative to the server's timezone setting.
Unless you are dealing with future data (beyond the year 2032) or conversely really old data, the most efficient mysql datatype is the timestamp datatype. Just be careful to turn off the automatic mysql timestamp functionality when you don't want or need it.
Internally to PHP you want to utilize the DateTime class which includes ways to convert from any one timezone to another.
The missing ingredient that has not been mentioned, is that in order for this to work for end users, you need to store their timezone, or utilize functions in the browser to read from the operating system the current timezone of their workstation.
Timezone strings can be stored, and then used after you fetch data from the server, to then convert it and show it to them relative to their timezone.
But again to be clear, all data should be stored as UTC, and this requires that the server be configured to utilize UTC. Well it's a bit more complicated than that, but you can save yourself a lot of trouble when you insure there isn't a mismatch. By the same token your web/application servers (and in fact all servers) ought to be set to UTC, and of course to sync their time using NTP. Most cloud based servers are going to do this by default.
Format doesn't matter as long as you keep your date as DataTime Object. Using PHP you can easily manipulate dates. My personal choice is using UTC offset because is easier for debug purpose. You can easier figure out if your time difference calculation is correct looking on the offset then on time zone name.
More information you will find under DataTime class.
Implementation is basically the same regardless format as long as you are using DataTime Object. This is the best way to calculate time differences in different time zones.
With datetime you get a rich set of tools for interacting with the data (including converting between timezones) and the opportunity to handle dates prior to 1st Jan 1970 and after 19th Jan 2038.
Although the same tools are also applicable to TIMESTAMP, the automatic timezone conversion can get messy.
A further consideration is that TIMESTAMP also acquires some subtle timezone conversions which get rather messed up if you move to maxdb mode or back. Indeed, datetime data will be more portable across different systems.
It does not matter as long as you are using UTC value. However, timestamps are better way to store data from different timezones as it always represents and stored as the standard time(UTC) irrespective of the timezone of client/server.
But, as you are taking the data from user's input it does not make a difference.
For the accurate standard time(UTC), you just need to convert it right according to the user's timezone.
You can retrieve user's timezone either from browser headers(which is a less accurate method) or you can ask the user himself(using a input).

php time from database

I use the php time() function to insert the time into a database after a user posts on my site. I store this value as an int. I believe the time() function inputs the number of seconds since like 1970. I now want to get the current time so I can subtract the two and get the time since the user's post. I have a two questions regarding this process:
Does the time come from the user's computer or somewhere on my server or somewhere else?
Is the time function stored as an Int the best way to do this?
Does the time come from the user's
computer or somewhere on my server or
somewhere else?
Its based on the server time
Is the time function stored as an Int
the best way to do this?
As the value returned is int, storing in int is the way to go.
the php time function refers to the severs internal time.
you can use timestamp or datetime for storing the time in DB.
From my experience both have a well performance.
Read about differences of time types:
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
See the PHP doc on time.
The time function returns an int, so using that and saving it is the simplest and most efficient way.
As PHP is executed on the server the servers time is used. Make sure to set your timezone in your PHP configuration. If you did not, using a verbose log level should warn you about it.
You may consider using a DATETIME column type to store this kind of data. It's pretty easy to recover the values in the way you want (ie: as an UNIX timestamp using MySQL's UNIX_TIMESTAMP function, formatted date/time using DATE_FORMAT...).
You could in some way override UNIX timpestamp's 1970 limit, for example storing and showing some guy's birthdate prior to 1970. Of couse, if you just store the data in a DATETIME column and use UNIX_TIMESTAMP to obtain an int, you did nothing.
It's the server time.
It depends on what you are going to do with it. An SQL query for a certain month may be better served by a DATETIME field.
It's best record int in DB and use mktime function to parsing in the page.

Best practices to insert time/time stamp in mysql

I've had some trouble choosing an efficient way to insert a time in mysql database.
I know mysql has its own timestamp system but it is not what I'm looking for.
I currently use date("Y-m-d H:i:s", time()); and it gets the job done.
But I would like to know what the standard is or what the best practices are to insert time that make it easier for retrieval later.
Thanks.
ps. I've searched the site for any dupe posts but I could not find any, if you think this is a dupe feel free to close.
you insert it the way mysql likes to store it, and on retrieval, you format it how you like (DATE_FORMAT()). You don't store it in some other format because that is how you want to display it, as that then breaks all the functionality of the date\time.
The best thing to do is store dates and times in the database in UTC and convert them to the appropriate timezone when displaying them. MySQL even has a special function for "now in UTC": UTC_TIMESTAMP().
When you use PHP's date function to format a Unix timestamp, you are outputting the representation of the date and time in the web server's timezone. That is rarely what you want, and it causes all sorts of problems whenever the web server's timezone changes, such as during Daylight Saving Time or if the web server is physically relocated to a different timezone.
You can store them as a MySQL timestamp and then use UNIX_TIMESTAMP() to convert to unix time for use in PHP, you can also use FROM_UNIXTIME to convert from unix time to a MySQL timestamp when inserting.
SELECT UNIX_TIMESTAMP(`field`) AS `unix_timestamp` FROM `table`;
INSERT INTO `table` SET `field` = FROM_UNIXTIME(unix_timestamp);

What's the best way to adjust for local timezones?

Maye I am wrong to use now() to get timestamps when storing data?
When I display date/time to the user, of course he wants to see a local time, and if he inputs time related data, rather than me using now() then he will be inputting local date/time.
Why code is getting muddled with conversations - what's the best practice for handling timestamps? UTC/locla time? How & when to adjust?
Just store all the dates in timestamp mysql column type, which can handle all timezone issues, and mysql will do all work for you.
So in the begin of your application startup all you need is to specify what timezone you need the dates belongs towith query:
SET time_zone='Asia/Vladivostok'
For example.
Also, in this case you should not get any timestamps from php, if you need to insert current time - you have to use mysql's NOW().
That's all.
Store all the dates in one time zone so they're consistent. UTC/GMT+0 is good for this.
Then use CONVERT_TZ to convert input to UTC/GMT+0 or from UTC/GMT+0 to a user's time zone.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
Since all you've asked about are SQL functions, you should tag the question with the RDBMS you're using (MySQL?) instead of PHP.

Categories