Is it faster to use the mysql query:
SELECT CURDATE() as today
or the PHP statement:
$curdate = date('Y-m-d');
Does the same answer apply to using date() VS MySQL's NOW() and CURTIME()?
If you're simply doing the query to get a date into a PHP script, then use the PHP function. In both cases, PHP and MySQL will call the system clock, mangle that time value into the formatted string, and return it. The MySQL version will have the added overhead of query parsing/compiling, and the roundtrip from PHP->MySQL->PHP. And if you're talking to MySQL via TCP socket, you've got added overhead of building/sending/receiving a TCP connection and packets.
On the other hand, if you're using that data value within a query, you'd be better off keeping it within MySQL. For instance, by random chance, you may start a script immediately before midnight, so that PHP generates "May 24/2011 23:59:59.999" for its timestamp, but the query doesn't execute in MySQL until "May 25/2011 00:00:00.001", so now the dates don't match.
It really depends.
It's almost always faster to keep a functions result inside its native habitat.
If you're going to use the date inside php, use the php date() function.
If you're going to use the date in a query use the MySQL NOW() function.
If php and MySQL run on different machines, definitely keep the data inside each machine for as long as possible. The roundtrip on the network will dwarf all other considerations.
It a good rule of thumb to strive for the minimum amount of network traffic.
if it is an INSERT statement it's better to use the mysql built-in functions but if it's a SELECT, it faster to use the php function 'date();'.
If the question is "in the PHP app, should I get the current date through mysql_query('SELECT CURDATE() as today'), or with $curdate = date('Y-m-d')?", then definitely use the PHP statement - the overhead for database roundtrip alone will dwarf that one call to a simple built-in PHP function (plus network latency if appserver != dbserver), that's not to mention the additional code you'll need to get the db result back (mysql_fetch_*() et al.).
You can try this at home ;) and measure the difference (which I would highly recommend), but IMHO date will be faster every time, barring some crazy convoluted scenario.
The PHP one is faster. Issuing a query to MySQL just to enquire as to the current date/time entails a round trip of data between PHP and the running MySQL server, which is considerably more work for the system than just PHP doing it itself.
Whichever method causes the least communication between the two platforms will be the faster one.
If the result of the statement is to be updated or inserted into the database, use CURDATE().
If the result is to be used in PHP only, use date().
Related
I'm working with Drupal 7, PHP, and MySQL, and trying to get my head around timezone issues when querying from the MySQL database.
Drupal handles dates pretty well out of the gate: all dates are stored as UTC timestamp int's in the db, and timezone conversion happens on a per-user basis via a timezone setting in each user profile, using PHP 5's built-in timezone capabilities (so each time a PHP script is run the script's timezone is set to the current user's timezone).
So this is all fine and dandy and fairly painless as long as we stick to PHP.
Things start to get tricky when we bring in MySQL, since there doesn't appear to be a way to perfectly synchronize the current PHP script timezone with a given MySQL query. It seems like best practice dictates handling ALL timezone conversion in PHP: only ever querying the database for the raw timestamps, and then converting in PHP as necessary.
This seems reasonable in most cases (even if a bit slower at times), but what am I supposed to do with MySQL GROUP BY [date] queries? For instance, I'm building a module to handle analytics, and frequently want to do things like:
GROUP BY YEAR(FROM_UNIXTIME(u.created)), MONTH(FROM_UNIXTIME(u.created))
So we run into the timezone issue...
Possible solutions that have come to mind:
Hard-code a timezone: Use date_default_timezone_set() within my module to insure that the PHP timezone is always set to the system timezone (so MySQL timezone = PHP timezone). In other words, the analytics timezone will be hard-coded, rather than respecting the timezone of the user viewing the analytics. This really isn't ideal, since we want users in multiple timezones to be able to access the analytics using their timezones. Also, date_default_timezone_set() seems to mess Drupal up, as it sets the timezone for the entire script, instead of just within a particular function...
Forget about using GROUP BY in the queries: just fetch all the raw data from the db (be there tens or hundreds of thousands of rows), then group the results by date in php using for loops... this solution seems like it would be significantly more resource intensive, slower, and somewhat ridiculous.
So I guess what I'm asking is, have I missed something? Is there a best practice here that I'm not aware of?
Thanks a ton for any help!
I would consider an approach such as this
SET time_zone = '+02:00';
http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
And have
GROUP BY FROM_UNIXTIME(u.created, '%Y-%m');
Since FROM_UNIXTIME bases it's time on time_zone, this should give desired result.
To undo the time_zone change afterwards, consider saving SELECT TIMEDIFF(NOW(), CONVERT_TZ(now(), ##session.time_zone, '+00:00')); first and then set it to saved value afterwards.
I am developing online shopping system. Only UK customers can place an order from the website.
I am wondering which is best method for me?
date_default_timezone_set("Europe/London");
$time = time();
or
using mysql function now() ?
Sometime customer can select a time for delivery or collection.
Note: In the UK, we change the time twice a year!
If the time is being sent to the database, use NOW(); less overhead, and the server time zone is hopefully always going to be correct and less mutable than PHP's time zone. If we're just talking about display, without actually doing database work, then it's excessive to run a mysql query solely to get the time.
In PHP I usually do the following:
date_default_timezone_set('GMT');
And then, upon connecting to the MySQL server, I execute the following query:
'SET time_zone = "' . date_default_timezone_get() . '";'
This makes sure that both PHP and MySQL are using the same timezone, so NOW() and date('Y-m-d H:i:s') should both yield the same result.
Regarding the daylight changes, they shouldn't be a problem (if you keep your software updated).
One massive consideration in this question is whether the times are the same between PHP and MySQL?
If the two are running on the same machine then the answer is likely to be 'yes', but if they're on separate machines then there's a strong possibility that they may in fact be different.
Consider a scenario where dates are written to a database using the MySQL NOW() function, and separately you have a query asking for all entries made in the last 24 hours, building the time in the query using the PHP date functions. If the time on the PHP server is out of sync with the SQL server, it opens up the possibility that you may miss records from your report (or get them doubled-up on consecutive days, depending on which way out of sync they are). This could lead to deliveries being missed, etc.
The upshot of this is that you should be careful to be consistent with your use of dates (and in particular datetimes). It doesn't really matter whether you use the PHP or MySQL date functionality, but you should try to use the same platform to query as you used to update.
Of course, it's not always going to be critical in this way, and you can be pragmatic about it - sometimes it's just too inconvenient to go back to the DB, just to find out what the time is! But when it's important, you should be careful.
Naturally, if the two systems are on the same server, this is a non-issue, but you shouldn't assume this will always be the case.
When building PHP applications I always end up having trouble trying to get everything to play right with server times and timezones.
I generally have a simple timestamp-like field on most of my records that isn't updated - just static for reference purposes. I use it to track when events happened, when users registered, when comments were created etc.
I have been trying to follow the best practices of using a Datetime field to store this value. The problem is that when using different servers they often have different timezones so the datetime's don't match up even close unless I add more code to offset the differences. This can also be a problem when using MySQL replication and NOW() queries since their is often a lag.
I'm wondering if I should go back to using ints since they don't seem to care anything about timezones and only require the server clock is set. The downfall is that all those MySQL date/time functions (I never use) can't be used which might be a problem in the future. The upside is that I can cut the storage space in half by moving back to 4byte ints instead of datetimes.
People also mention that ints will only work until 2037 - why is that a problem? Who expects to be using PHP + MySQL in 2037?
Is there anything I am missing? Is it better to store reference times in an agnostic way like Unix timestamps?
I use date/time fields in all my database work but store everything in GMT. Pretty much the first opportunity my code gets it converts something into GMT, and does all its internal math in gmt, etc. The only time I convert it back out of GMT into local time is when displaying to the user. PHP has unixtime() which is GMT, plus gmstrftime and gmdate, pretty much anything you'll ever need.
I have some dates/events in a database, and I'd like to pull them out ordered by month (year doesn't matter) - right now all the timestamps are in unix in a column named eventDate. How can make that query?
SELECT * FROM calendar ORDER BY eventDate
Obviously that sorts them, but I want to make sure all events across all years are grouped by month - then obviously need to arrange them January, February, March, etc.
Any advice?
Thanks!
You could use FROM_UNIXTIME() function + MONTH() function.
SELECT MONTH(FROM_UNIXTIME(0));
-- 12
But there's no reason to store a unix timestamp over a real timestamp (YYYY-MM-DD HH:II:SS). RDBMS have functions to manipulate dates and if you really need the unix timestamp (I never do, TBH), you can use the UNIX_TIMESTAMP function.
There are plenty of extremely good reasons for using unix time. Good database design hugely impacts how expensive it is to run databases and website, especially successful busy ones.
The best case I know of is..
a really busy server(s) and where time data is required to be stored but the time data is actually accessed rarely compared to the number of reads and writes actually going on in the db. It takes cpu resources to do all the manipulation of that time data, So don't unless you absolutely have to.
A real life example is my own. We needed 4 front end web servers and were going to be adding more. they were old too and needed updating. looking at 6 replacement servers that would be needed it was going to cost us a bundle. decided to look about what we were doing. We now have 2 front end servers instead of 4 or 6. what it took? optimizing the database structure and queries and the code that inserted and read data from them.
One example that took your exact consideration in mind... changed 1 line of php code, changed the time column to unix instead of yyyy-dd-mm hh:mm:ss, added an index to the time column and that one operation went from 0.08 seconds to 0.00031 seconds start to finish.
The multifold impact on cpu resources was huge. the next queued up operations executed faster... etc.
That is why people have jobs as database designers... it really is important.
of course if your website is slow and not busy.. probably no one will notice.
But if you are successfull, it WILL matter.
If you've got a busy site and your servers get sluggish... look at things like this. You might not need a new box or more memmory, you just might need to clean up code and optimize the db.
Timestamps, their form and how they are used and stored DO MATTER.
I am writing an app that allows people to schedule things for certain times and then displays them. The time of the event is stored in the database as an SQL TIME, because there are things I'm doing in the DB that need this structure.
However, on the output page I want the time to be in 12:00 am/pm format, but I don't want to run a conversion script every time I step through the database output loop.
I don't want this:
while (database loop){
convert to clean time
output event info, with clean time
}
because I think it is too much strain and unneccesary. Is there a way to do this better short of storing the time in the db twice (once in 24 hour and once in 12)?
You do not state which DBMS and which platform, but most modern ones would have some sort of CONVERT or CAST function that you could use, either at the DB level, or while processing your output.
for sql server use convert with style 100
select convert(varchar(30),getdate(),100)
Feb 6 2009 1:44PM
The output page is your presentation layer. Don't mix up presentation issues into the database layer. Especially don't force a denormalisation just for presentation's sake.
i dont want to run a conversion script every time i step through the database output loop
Whyever not? Depending on what language you're using it shouldn't be any more work than just sending the time through a strftime() operation before plonking it onto the page. It's not going to be slow.
Converting times and dates on the database takes very little resource and will be much faster than doing it in PHP or JavaScript. I would use the date and time functions provided by your database e.g. DATE_FORMAT(date,format) in mySql.