P
P
Peter2021-10-10 00:36:29
PHP
Peter, 2021-10-10 00:36:29

Where to get the current date for SQL query - from php or mysql?

There are requests, of various types, where something like is used:
WHERE `date` = CURDATE()

the question is, for speed or for other reasons, is it better to use
$Date = (new DateTime())->format('Y-m-d');

WHERE `date` = $Date

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Timur, 2021-10-10
@XAKEPEHOK

There will be no difference in performance, here it is more convenient for you, only if you use the second option - use the bindings https://www.php.net/manual/ru/mysqli-stmt.bind-par... or even better, use not naked mysqli, but some kind of ORM.
As for the difference between these two methods, it can manifest itself in time zones. For example, mysql server can have Vladivostok time zone, but in php you will have Moscow time zone - then you will get different results. This problem can be avoided if you set the correct time zone for both the mysql session and php when initializing the application
https://stackoverflow.com/questions/930900/how-do-...
https://www.php.net /manual/en/function.date-default...

N
neol, 2021-10-10
@neol

If you execute a query with CURDATE() (and even more so CURTIME()) 10 times, then these will be slightly different queries, possibly with different results. In some cases, this behavior is needed, in some it is better to specify the exact time. For example, if you need to sample a large data set in chunks, then it is better to use the second option.

V
Vladimir, 2021-10-14
@v__V__v

If in terms of speed, then definitely CURDATE () / NOW () / CURTIME () - in this case, you simply pass a string constant in the request (who will say that this is not a string constant - does not understand anything in programming), in the second - it is first created an object with all the overhead, then its method is called, which returns the result, which is placed in a variable, which is then extracted from it and substituted into the query, which, after a bunch of extra gestures, finally goes to the DBMS. And php is still not a binary code, despite all the tricks of the developers. And in the first case, all this is not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question