Since the calculation work can be performed by either PHP or the DB, restrict the number of times you touch the DB to a minimum.
Due to that type of consideration, if the calculated date is calculated using dates already in the database, and is used as a filter of some kind for when retrieving info from the database, it can be better to have the database perform the calculation work.
In other words, where practical, use PHP.
If you’re already communicating with the DB and the date work can be easily incorporated in to the same request, use the DB.
Try not to request dates from the DB, calculate using PHP, then request info using the calculated dates. That uses two trips to the database. Try to do it with just one trip to the DB instead.
I would only make one round trip. I would either change the SQL to calculate the date or I would let PHP calculate the date. {date1} is provided by the user {date2} is calculated out as x number of days before or after (which is also provided by the user). In the past I’ve used PHP, but I know more about SQL than I used to. So when I started this project, I was just wondering which was is faster. We’re expecting the database to be getting a lot of hits already, so I’m assuming that PHP would be the faster way to go. Also, I’m assuming that a database like MySQL would take more system resources than the PHP compiler…
If you are only going to use MySQL then sure, let MySQL handle dates but what if at any point you decide to replace MySQL with a different database? No all databases have the same Date/Time functions as MySQL. So for the sake of portability handling dates in your program instead of in the database is a better approach.
At the end it’s up to you - they are equally fast, MySQL dates are not faster than php dates functions.
If you just store the dates in unix timestamp then the code does not have to change in case you change the database. Unix timestamp is just an integer and therefore very easy to use in the query using greater than or less than operators. All databases support < and > in queries as far as I know.
It works either way, but I prefer to use yyyy-mm-dd for the dates as they are understandable when you view the data, and <> comparisons still work as intended.
So the DB casts them prior to comparison… I always have a fear of the DB doing the opposite and casting the stored date to string for comparison… I never trust MySQL to do the right thing lol.
In most cases a timestamp isn’t appropriate as an output (and in this example we’re looking at user interaction with dates) -
would it not be faster to do a text comparison then to convert a string to timestamp, make the comparison, and the convert the resulting timestamp back to a string.