MYSQL SELECT records older than 1 year ago - php

I try to get a list of all records that are older than 1year ago from my database, the field for expired_contract has next information.
expired_contract DATE NOT NULL
So it takes the DATE in the next format: YEAR-MM-DD, next i have the sql that i cant get it working sadly.
$sql = "SELECT *
FROM My_Contracte
WHERE expired_contract >= DATE_SUB(NOW(),INTERVAL 1 YEAR)
ORDER BY id_contract DESC";
I tried a lot of "WHERE" commands but none worked as i expected. Can you help me get this working? I'm looking on this for about 5hours i need exact command to get it worked.
The $sql gets me something but takes it wrong, i get dates like: 2015-10-01, 2016-10-01 and date like 2014-09-30 doesn't show up.
Basically i want to show dates like:
If today is 2015-10-01 i want to see dates older than 1year ago so from 2014-09-30 and not showing dates like 2015-10-01, 2016-10-01.
Maybe do i have to edit something in database?
Looking for your help, thank you!

You have to use lower than instead of greater or equals:
$sql = "SELECT * FROM My_Contracte WHERE expired_contract < DATE_SUB(NOW(),INTERVAL 1 YEAR)

SELECT SUM(impressions) AS impressions FROM My_Contracte where DATE(expired_contract) BETWEEN DATE_SUB( CURDATE( ) ,INTERVAL 1 YEAR ) AND CURDATE( )

SELECT * FROM My_Contracte WHERE (expired_contract NOT BETWEEN DATE_SUB(CURDATE(),INTERVAL 1 YEAR) AND CURDATE()) and expired_contract<=NOW() ;

Related

Calculate the difference b/w two months data

I have a mysql table orders in that I have a column order_date which is current time stamp(2016-08-17 00:00:00.000000). now I want to select or count the data's entered this month and the previous month, after this I can find the difference between these two months I am using this code and it is not working.
$sql="SELECT * FROM order WHERE order_date > DATE_SUB(NOW(), INTERVAL 1 MONTH)";
$result = $this->db->query($sql);
return $result;
this is not working an mysql error is produced.
Try
$sql="SELECT * FROM order WHERE DATE(order_date) LIKE DATE_SUB(CURDATE(), INTERVAL 1 MONTH)";
$result = $this->db->query($sql);
return $result;
i think this Link[http://sqlhints.com/2015/07/10/how-to-get-difference-between-two-dates-in-years-months-and-days-in-sql-server/] will help you
Use this. Hope it helps what you want. Thanks
$todayDate = date('Y-m-d');
$todayMonth = date("m", strtotime($todayDate ));
$previousMonth = $todayMonth - 1;
$sql = "SELECT * FROM order WHERE MONTH(order_date) BETWEEN '$todayMonth' AND '$previousMonth'";
First, the following is the correct logic to get all values from the current month and all of the previous month:
select *
from orders o
where order_date >= date_sub(date_sub(curdate(), interval day(curdate) - 1 day), interval 1 month);
Then, use conditional aggregation for comparison. Here is an easy way:
select sum(month(order_date) = month(curdate())) as cur_month,
sum(month(order_date) <> month(curdate())) as prev_month,
(sum(month(order_date) = month(curdate())) -
sum(month(order_date) <> month(curdate()))
) as diff
from orders o
where order_date >= date_sub(date_sub(curdate(), interval day(curdate) - 1 day), interval 1 month);
Note: I don't fully see the utility of comparing a partial month (this month) to a full month (last month), but that is what you seem to be asking for. If you are asking for something different, then ask another question with sample data and desired results.

Getting Newest Records from MySQL (7 days)

I am trying to grab the newest records from my table. I want all of the records that happened in the past 7 days. Here is what I have so far to start with.
$query = "SELECT * FROM mlg_logattempts AS a WHERE a.ts = (SELECT MAX(ts) FROM mlg_logattempts AS b WHERE b.ts > NOW() - INTERVAL 5 MINUTE AND b.name = a.name)";
I have used intervals in the past but an unsure how to make this work now. Can someone show me the proper way to request the past 7 days records? I do have a timestamp field.
UPDATE
Unfortunately I realized the command I shared with you. I do not have any of the above fields. The only date field I have is "date". no a or ts.
You could use mysql date_diff() for dates
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff
but since you use timestamps, the interval is a good solution:
b.ts > unix_timestamp(CURDATE()-INTERVAL 7 DAY)
Supposing that the date of login attempt is b.ts and it's formatted like 2013-08-20 03:08:
$past7days = date("Y-m-d H:i:s",strtotime("-7day"));
$query = "SELECT * FROM mlg_logattempts AS a WHERE a.ts = (SELECT MAX(ts) FROM mlg_logattempts AS b WHERE date >= '$past7days' AND b.name = a.name)";

How to get today's / yesterday's data from MySQL database?

I would like to retrive a TODAY'S data from the database, but I don't know how to do it. I would actually want to get the data from NOT the past 24 hours, I just want today's data (so based on the actual server time).
I would also like to get data which was yesterday. Can anyone help me how to do it?
Sample code:
"SELECT id FROM folk WHERE time = ???"
Thank you in advance!
I think you are looking for this:
"SELECT id FROM folk WHERE DATE(time) = CURDATE()"
time must be a field in you table that holds a reference to the row.
update
To get yesterdays additions:
"SELECT id FROM folk WHERE DATE(time) = CURDATE() - 1"
update 2
To get all additions this month:
"SELECT id FROM folk
WHERE MONTH(time) = MONTH(NOW()) AND YEAR(time) = YEAR(NOW())"
reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
SELECT id FROM folk WHERE DATE(time) = DATE(NOW());
SELECT id FROM folk WHERE DATE(time) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY));
provided that 'time' has a proper date-time type
Try something like this>>
SELECT id from folk WHERE DAY( date ) = EXTRACT(DAY from (NOW() - inTERVAL
1 DAY ) )
Refer this link
http://www.webmasterworld.com/forum112/278.htm
As you are using timestamp:
"SELECT id FROM folk WHERE time >= ".mktime(0, 0, 0)
That will select all data since beginning today.
If you want to get all date not for today, you would do
"SELECT id FROM folk WHERE time < ".mktime(0, 0, 0)
To select data from yesterday, you would do:
"SELECT id FROM folk WHERE time < ".mktime(0, 0, 0)." AND time >= ".mktime(0, 0, 0, date('m'), date('d')-1, date('Y'))
If you were to use DATETIME, just for reference, it would be something like:
"SELECT id FROM folk WHERE time >= '".date('Y-m-d').' 00:00:00."'"
Get current date by using something like following query
SELECT *
FROM your_table_name
WHERE DAY('.$colum_name.') = DAY("2018-05-02")';

get next upcoming game, display on mondays

There will be games at saturdays but not every weekend. I Want to show on a new week if there is an upcoming game that following saturday.
I was thinking of something like this to check 6 days ahead if we are on ex monday, if there is a game that saturday it should find it. But of course it lacks parts, just a start but Im stuck. As for now it finds the next game which is 1 month away, it should only show if there is one that week.
"Select * From games Where date > DATE_ADD(CURDATE(),INTERVAL 6 DAY)"
You can use PHP's DateTime class to find the date for next Saturday:
$nextSaturday = new DateTime('next Saturday');
From there, just select where the date equals $nextSaturday->format('Y-m-d') to find the games (if any) for next Saturday.
What you want to ask the database to fetch is "all games WITHIN the next 6 days" really
SELECT * FROM `games` WHERE `date` >= CURDATE()
AND `date` <= DATE_ADD(CURDATE, INTERVAL 6 DAY)
... or you could use BETWEEN ...
SELECT * FROM `games` WHERE `date`
BETWEEN CURDATE()
AND DATE_ADD(CURDATE(), INTERVAL 6 DAY)
[edit]
Having just worked out what you meant by "display on mondays" in the question title ... you only actually want to execute the query on Mondays :)
So you'll either only want to run the query on Mondays (done at the application level) or run the query with an AND DAYOFWEEK(CURDATE()) = 2 in it so it'd be something like
SELECT * FROM `games` WHERE `date` >= CURDATE()
AND `date` <= DATE_ADD(CURDATE, INTERVAL 6 DAY)
AND DAYOFWEEK(CURDATE()) = 2
Although that's rather inefficient as you'll always run the query even if there's no need to - it would be better to have the application only execute it on Mondays.
In which case you're better off with drrcknlsn's solution using PHP's DateTime object and doing something like (or munging the whole thing into a Cron job):
if(date("N") == 1) {
$oNextSaturday = new DateTime('next Saturday');
$sFetchUpcomingGames = "SELECT * FROM `games` WHERE `date` = '{$oNextSaturday->format('Y-m-d')}'";
//execute the database query and perform relevant outputs, and so on
}

PHP and MYSQL having issues with my query!

I am having some issues with the following query, the issue is that I need it so it displays the courses for the current day until the end of the day not just till the start of the day like it does currently. Basically users cannot access the course if they are trying to access the course on its enddate so i need to some how make it so that they can still access it for 23 hrs 59 mnutes and 59 seconds after the end date I think I have to add some sort of time to the NOW() to accomplish this but im not sure how to go about this.The query is as follows:
if ($courses = $db->qarray("
SELECT `CourseCode` AS 'code' FROM `WorkshopUserSessions`
LEFT JOIN `WorkshopSession` ON (`WorkshopUserSessions`.`sessionid` = `WorkshopSession`.`id`)
LEFT JOIN `WorkshopCourses` ON (`WorkshopSession`.`cid` = `WorkshopCourses`.`cid`)
WHERE `WorkshopUserSessions`.`userid` = {$info['uid']} AND `WorkshopUserSessions`.`begindate` <= NOW() AND `WorkshopUserSessions`.`enddate` >= NOW()
ORDER BY `WorkshopUserSessions`.`begindate` ASC
")) {
Any help would greatly be aprreciated!
Thanks,
Cam
I think you need to modify it like this
enddate + INTERVAL 1 DAY >= NOW()
Ofcourse this adds 24 hours, for 23:59:59 just change >= to >
It sounds like you just need to use date_add
DATE_ADD(`WorkshopUserSessions`.`enddate`, INTERVAL 1 DAY) > NOW()
Try replacing:
AND `WorkshopUserSessions`.`enddate` >= NOW()
with
AND DATE(`WorkshopUserSessions`.`enddate`) = CURDATE()
Hope it helps.

Categories