MySQL: getting rows for a given date - php

I have the following query:
$yesterday=date("Y-m-d",mktime(0,0,0,date("m"),(date("d")-1),date("Y")));
$sql = "SELECT messages FROM user WHERE sent_date='".$yesterday."'";
With it I select all the messages sent to the users yesterday.
In my database sent_date looks like: 2010-12-28 11:55:30
But with $yesterday I get: 2010-12-28
So I get 0 results.
How can I modify my query so I can select all the messages from yesterday no matter the hour?
Thanks a ton

You should use MySQL Date functions for that (assuming the column is a datetime).
SELECT messages FROM user WHERE sent_date = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY);
or always from 00:00
SELECT messages FROM user WHERE sent_date = DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL 1 DAY);
If this is not giving any results, please edit your question with more info. You exact schema, how do you insert data and ensure that there are valid rows inside the table.

Perhaps by using
$sql = "SELECT messages FROM user WHERE date(sent_date)='".$yesterday."'";
That way you don't use the time in the datetime for comparison.

You could do a BETWEEN and put in a starting and ending time concatenated on the $yesterday...
Actually... what the next post suggests is better if you want the full date.

Related

Will specifying a SUBTIME interval in MYSQL prevent the query from unnecessarily going through the entire table?

Please tell me, if I specify an interval like such: subtime(now(), INTERVAL 1 day) inside a MySQL SELECT query while having a proper datetime column to use as reference - will this prevent from the query to look through the entire table (over 100,000 records in my case) each time it runs but rather look through records made only the past 24 hours? Is DESC order needed for the datetime table or such? Also, if I have SUM(column) in the query, will it also run only for the interval specified?
Edit: If I just would like to use the above mentioned SUM to sum a column where there only are integers of value "1" - would it be better to simply check how many rows the SELECT query returns with mysql_num_rows - is it more efficient in combination with the time interval setting?
Thank you!
It will in fact prevent MySQL to go through the whole table but not if you just subtime() in the SELECT-part. Instead you have to do something like this:
SELECT * FROM myTable
WHERE myDateCol BETWEEN DATE_SUB(now(), INTERVAL 1 day) AND now()
The query will now select only rows one day old. Add a B-TREE index on myDateCol to speed things up:
ALTER TABLE myTable ADD INDEX myIdx USING BTREE (myDateCol)
See MySQL doc on that topic

Database living in the past?

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?

Group and manipulate based on multiple columns

I have a table that inserts a row when a certain function is used on the site and stamps the date.
code-/----date----/--type
-----/------------/------
--1--/--2012-2-1--/-used
--1--/--2012-2-3--/-saved
--1--/--2012-1-3--/-printed
--2--/--2012-2-1--/-used
--2--/--2012-2-2--/-printed
I have to report the number of times code 1 was (printed or saved or used) today, or yesterday, or last month (date range)
I am starting with this:
$stat_query = mysql_query("SELECT code, type, date FROM tracking WHERE code IN ('$htL','$htG','$htR') GROUP BY code, type, date");
I use the IN operand because each user has 3 codes to track with limitless date entries for each type.
I really am lost as to what to do here.
You'll need to construct the date ranges and modify the query. Below is an example of showing the count for code in the past day:
SELECT `code`, COUNT(`code`) as code_cnt
FROM tracking
WHERE
`code` IN ('$htL','$htG','$htR') AND
`date` BETWEEN DATE_SUB(now(), INTERVAL 1 HOUR) AND now()
GROUP BY `code`
Check out the DATE_SUB documentation for further help
GROUP BY code, type, date in this example makes it to return only one record. Because all code rows would be summerized in distinct output row, also type would be reduce more and more. Please check your GROUP BY fields.

Query to select records from a database that were created from a certain time in the past until now

I'm relatively a newbie, would appreciate help :)
I am looking to find entry(ies) from a mysql table which were created some time between now and a certain timestamp in the past. This time in the past is stored in a variable (say $timeinthepast, a few hours ago or yesterday, whatever). And the column 'timecreated' in the table is the timestamp of the creation of entry.
Would the following work? If not, what would?
Thanks!
<?php
$query = mysql_query("SELECT * FROM table1
WHERE timecreated = DATE_ADD(NOW(), INTERVAL -$timeinthepast)");
?>
I am basing this on: Query to select records from a database that were created within the last 24 hours
As long as $timeinthepast is valid (1 MONTH, 2 HOUR, e.g.) in the sql you can try BETWEEN
$query = mysql_query("SELECT * FROM table1
WHERE timecreated BETWEEN
DATE_SUB(NOW(), INTERVAL $timeinthepast) AND NOW()");
I find that the between syntax is the most freindly to use. I have not tested this sorry :)
Select * from `table1` where `timecreated` between DATE_SUB(NOW(), INTERVAL 1 month) and NOW()
You will need to make your time in the past a whole unit of some description.

MySQL date/time calculation

I have a date and time column in my mysql table called start_date and start_time respectively. I want my users the ability to set reminders for themselves to be sent X hours before start_time, min. 1 hour and max 24 hours.
I'll be running a CRON script to send these reminders. Right now I do:
SELECT * FROM auctions WHERE start_date=CURDATE() AND status='0'
To get all the auctions that will be starting today and haven't yet started. My question is, how can I figure out if the time now is X hours before start_time so I can send them a reminder if it is.
Any suggestions at all?
Something like this:
SELECT col1, col2, col3
FROM records
WHERE (records.startDate BETWEEN NOW() AND ADDDATE(NOW(), INTERVAL 9 HOUR))
AND (records.status = '0');
Is there some reason why you can't just use a simple timestamp field instead of one for date and one for time. That way you could find all the ones that start in the next 5 hours (say), by doing
select * from auctions where start_ts between now() and now() + interval '5 hours';
Note: the interval syntax varies slightly between databases, and that's the one for postgresql, so you might have to change it slightly for mysql.
I actually did it this way before all the answers were sent and its working. Because i'm on a deadline I can't go back and change it :)
$sql="SELECT HOUR(ADDTIME(CURTIME(),'$hour')) as remindHour, HOUR(CURTIME()) as curHour";
$result=$this->db->query($sql);
extract($result->getAllSingle());
if ($remindHour <=$curHour) {
// Send reminders
}
Can you use unixtime to save the time?
Since PHP has a wonderful function called strtotime.
Within in you can say. strtotime("+20 hours") and get the unixtime for 20 hours from now.
Then its just a matter of which field is larger than the other, if so, send the notification.

Categories