I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?
example:
$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';
vs
$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';
Any function containing CURDATE() will not be cached. Source
Hardcoding the date should still be cached as far as I can tell. Though you might want to consider using the prepare functionality instead of splicing strings into your query (for sanity and security sake).
It's quite simple actually. The MySQL server does not see your PHP code so it'll receive one of these:
SELECT id FROM table WHERE publish_date = '2010-01-18';
SELECT id FROM table WHERE publish_date = CURDATE();
It will not read your intentions either. For MySQL, '2010-01-18' is a string and is deterministic: its value is always '2010-01-18'. However, CURDATE() is not deterministic: its value varies depending on the date when you run it. Thus the first one is cacheable and the second one is not.
I personally preffer first way, because it give clear head about server time (time zone), my mysql server happend to be 10h earlier when promissed :)
localtime in your PHP script will apply in SQL
Related
I'm trying to get a specific show description from my DB but I really don't know how, I know i'm new into this, the table (guide) have 2 DATETIME values "start" and "end"
If I use this:
$sql = mysql_query("SELECT * FROM guide WHERE start >= CURDATE()");
Only return the first value from the table, and inclusive its the wrong value, please I need some help to get this, because I don't find a solution from other on this web
You should be able to use mysql's between function to pull the records in the current time range.
select * from guide where now() between start and end
To limit the returns you can add in additional parameters, this may give you back no results though so have a default value.
select * from guide where channel = $channel_ID and now() between start and end
You also should look into parameterized queries and updating your driver. Having variables in your query isn't the best practice.
Assume that your webserver is detached from your database server. Their clocks might not be properly synchronized (down to milliseconds etc.).
You perform an insert such as "INSERT INTO sometable (VALUE,VALUE2,DATETIME) VALUES ("something","something else",NOW());"
Is there any way to get the timestamp generated by MySQL back into PHP? In the same fashion as when using $sqlObject->insert_id to get the AUTO_INCREMENT value of the last inserted row.
Edit:
I realize I could just use the insert_id and run a SELECT to get the timestamp, but this would require that I run another statement. I am wondering if it is possible in a single statement.
You can not get the direct value but you can do it via 2 ways.
1) Make a select query like select now() as cur_time. and take its value and use in the 2nd query. [ Its possible that you might get different time for this solution, SO i will suggest not to go with this solution and better you go with option 2. ]
2) After inserting the data get its ID and and make a query and get the inserted date time.
If your PHP and MYSQL server date time are same then you may use php's date function to get the current date / time .
I have events in my MySQL database wich all have a date. When I perform a SQL query to get all the events in the future, I get an error... Although, the date of the events are in the future. When I change my SQL request to select dates in the past, I get those from the future...
The SQL statement below has worked before, but for some reason it stopped working...
I use this SQL request:
$sql = "SELECT * FROM calendar WHERE date >= CURDATE() order by `date`";
I get an empty array as result...
However if I change the query to this, I get all the events in my database:
$sql = "SELECT * FROM calendar WHERE date <= CURDATE() order by `date`";
This is my database data. In my opinion, all data are in the future...
The format of the date table is a default date-type:
When I ask my server about the time echo date("Y-m-d"); I get todays date as result...
So where do I make a mistake?
You may be checking the wrong date field. Do you have a created date as well as a scheduled date?
I could be crazy from the cold medicine I am on at the moment, but your date table can't possibly be the date of your calendar items, the id filed is only an int(2), that seems kind of small.
maybe something simplier? I notice the column name in your table is date, which also is the name of a function date() that returns the date part of a datetime value. If thats the case
$sql = "SELECT * FROM calendar c WHERE c.`date` <= CURDATE() order by `date`";
would do the trick. Even if not mysql itself, the gui app youre using (seems like phpmyadmin to me) might get confused.
(btw, you forgot the closing tick of date in the order by clause)
getting an empty set is meaning nothing is found matching. I would look at your formatting of your date. The only other thing i was thinking is that it is comparing an unmatched type so just returns an empty set.
use DATEDIFF :
DATEDIFF
WHERE DATEDIFF(date, CURDATE) > 0
Before you make your query, run this one:
SET time_zone = '-2:00'; // or whatever your time zone is.
Don't ask me how or why, but I've truncated my table and re-inserted some data and my query seems to work just fine:
$sql = "SELECT * FROM `calendar` WHERE `date` >= CURDATE() order by `date`";
So, despite the fact the problems seems to be solved by truncating my table, I would like to know the answer to the why-question... Anyone can provide me with it?
while fetching data from MySQL for today's date, what should be preferred why
1) "select * from table1 where created_dt Like CURDATE()";
2) "select * from table1 where created_dt Like ".date(Y-m-d H:i:s);
will it make any difference in execution time of the script, If i use MySql function instead of php function or vice versa
will it make any difference in execution time of the script
Definitely NO.
The difference would be pretty negligable, though generating the date in SQL would probably be marginally faster.
You should not be using 'like' though, since that is for partial string comparisons, and you are using a date field (which, internally, will be an integer). You are also missing two sets of quotes for your php date example.
But most importantly, if you are using a datetime format for created_dt, and then attempting to match by date using date(created_dt) or any kind of string comparison, you will not be taking advantage of indexing, and are likely to cause a full table scan. You'd be better using:
select * from table1 where created_dt between CURDATE() and date_add(CURDATE(), interval 1 day);
Which can take advantage of a btree index on created_dt to make your query perform considerably faster and more efficiently.
It would be best to use option 1 - date value computed on the database server because:
MySQL doesn't need to convert the string value from the query to a date, since CURDATE retrieves a DATE value
the PHP date function parses the parameter and formates the date and concatenates the result to the query string, which is surely a more complex task then the mysql CURDATE function which has no parameters and simply retrieves the date
In a MySQL 5.1 InnoDB environment, what is the best way to SELECT data based on date intervals?
Letting MySQL do it via something like DATE_SUB(CURDATE(), INTERVAL 5 DAY) > created_at
Or have PHP prepare the date before submission via strtotime?
I would do it via the query to MySql. That way, you keep the logic of selecting dates out of the PHP. The PHP just handles the display, and you get the advantage of smaller chunks of data coming out of the database as well.
I don't think it matters from performance point of view in this case. Your expression (DATE_SUB) will be evaluated just once. Another point is that your webserver and mysql server can use different timezones, so you may have different results.
I would keep as much logic closest to the database - it has more ability to do any optimisations. Also gives the ability to do change tables easier, change the use of PHP (perhaps java/C# ...) in the future. It also differentiates beteen database (for the data), PHP (for HTML delivery), Javascript (for user enjoyment), CSS (to make things pretty)
You can select a date range using BETWEEN ... AND ...
SELECT * FROM table1 t1 WHERE now() BETWEEN t1.startdate AND t1.enddate
or
SELECT * FROM table1 t1
WHERE t1.somedate BETWEEN DATE_SUB(now(),INTERVAL 1 DAY) AND now()
I prefer this syntax because it's so close to my mental picture of ranges.