How to compare dates from php database with the today's date - php

I have created a mysql table as shown below.
I would like to compare the dates in the table with the current date by using if else statement, and send notifications to the user one day before, one day after and one the same date
For instance, let's say today's date is 18/10, and expiry date for Milk is 20/10, so I want to send notifications on 19th, 20th, and 21st.
So, if you can help me with comparison code and the code for sending notification (such as email) that should be under if statement I would really appreciate it :).
My question might seem easy but I am new to php I do not have much information about it.
Here is my php code that I am trying to do
<?php
$first= new Carbon;
//$second= here I want the date to be collected from date column in the database
//X= The name of the item that will be collected from database (Item_Name) column
if ($second=eq($first+1))
{echo"X is going to expire tomorrow"}
// instade of dispaying the above sentence, i want it to be sent as email
if ($first=eq($second))
{echo"X is going to expire today!!"}
if ($first>eq($second))
{echo"X has EXPIRED already"}
?>
My table:
ID Item_Name Expiry_Date
1 Milk 2017-10-20
2 Chicken 2017-10-22
3 Meat 2017-10-25

You could use the DATE_ADD function to determine the interval.
SELECT
col1,
col2,
...
FROM
table
WHERE
`date_column` BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY);
You mentioned PHP, and I want to clarify that this is MySQL, and I'm assuming you have a cron job or the like setup to run a PHP script.
UPDATE:
Based on your updated question, you have two major choices, either do the processing in the database or in PHP. The decision is dependent on how you planning on using it, but can feasibly be done both ways.
-- MySQL --
SELECT
ID,
Item_Name,
Expiry_Date,
CASE
WHEN `Expiry_Date` < CURDATE() THEN CONCAT(`Item_Name`,' has EXPIRED already.')
WHEN `Expiry_Date` = CURDATE() THEN CONCAT(`Item_Name`,' will expire today.')
WHEN `Expiry_Date` BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' will expire tomorrow.')
WHEN `Expiry_Date` > DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' will expire after tomorrow.')
ELSE 'Error processing expiration date.'
END AS `Expiration_Message`
FROM
table;
Which would produce
ID Item_Name Expiry_Date Expiration_Message
1 Milk 2017-10-20 Milk will expire after tomorrow.
2 Chicken 2017-10-22 Chicken will expire after tomorrow.
3 Meat 2017-10-25 Meat will expire after tomorrow.
You could also do the string parsing and date addition in PHP which you seemed to start on. In terms of sending an email, PHP has a mail function, which How to send an email using PHP? might give you some guidance on. Now, I assume you want this to run on a schedule, so I would look into Execute PHP script in cron job.
Hope this helps with some more clarification.

Related

Mysql statement where not exists with time intervals

I am basically trying to get my app to report when items are not returned or overdue in a 5 day and 15 day window. After much trial and error the below coded is the best I could come up with. However, when I extend to 15 days I still receive items that were returned (hence not exists not working appropriately) based off of movieid. The goal is see items from checkout that have not been returned with a time frames to notify members of late dates. Any suggestions to improve this statement?
select movieid, dueback
from checkout as a
where NOT exists
(
select * from returns as b
where a.movieid = b.movieid
AND dueback < DATE_SUB(NOW(), INTERVAL 5 DAY)
)
ORDER by dueback;
CHECKOUT TABLE: checkoutid, outdate, dueback, movieid, customerid, payment
RETURNS TABLE: returnid, today, movieid
You can use BETWEEN using the two computed dates. See Between documentation, but you can do something like:
AND dueback BETWEEN DATE_SUB(NOW(), INTERVAL 5 DAY) AND DATE_SUB(NOW(), INTERVAL 15 DAY)
That way you will get all dueback that is between 5 and 15 days from it's date.

Check if supplied datetime value lies between a certain time interval

Scenario
UDPATE
Please ignore the commented section. After thinking for an alternative, I came up with this:
Let's say I have
$date = '2012-10-03 13:00:00'
The time interval range is
2012-10-03 12:00:00 to 2012-10-03 14:00:00
Now $date falls between the time range mentioned above. Any ideas on how to compare a date time with a range of date time? I've come across functions which compare either just date or just time but not both at the same time. Any help much appreciated.
/*I'm building a school timetable and want to make sure that a room cannot be assigned to two different periods if it is already occupied. I have datetime values of **`2012-10-03 13:00:00`** (the start time of a period. Let's call it **abc** for reference) and **`2012-10-03 13:30:00`** (the end time of a period. Let's call it **xyz** for reference).
My database table contains columns for room number assigned for a period and the start and end time of that period. Something like this:
room_no | start_time | end_time
5 2012-10-03 13:00:00 2012-10-03 14:30:00
This means for October 3, 2012 room 5 is occupied between 1pm and 2:30pm. So the datetime values that I have (abc & xyz) will have to be assigned to a room other than 5.
I'm at a loss of ideas on how to go about validating this scenario, i.e. make sure that the period with time interval between abc & xyz cannot be assigned room number 5.
Any help would be appreciated. Thanks in advance
PS : I'm not asking for code. I'm looking for ideas on how to proceed with the issue at hand. Also, is there a way a query can be build to return a row if `abc` or `xyz` lie between `start_time` and `end_time` as that would be great and reduce a lot of workload. I could simply use the number of rows returned to validate (if greater than 0, then get the room number and exclude it from the result)*/
if(StartTime - BookingTime < 0 && BookingTime - EndTime < 0)
{
// Booking time is already taken
}
You can do this in SQL with TIMEDIFF().
I'm working on something similar and perhaps an easier way to code it would not be using times but timeslots? The way I thought of doing it was a table bookings (date, slot ids, room) table slots (with maybe slot ID and TIME) and per booking use a certain amount of slots.. then when you look for when the room is available it shows you per date what slots are free.. Just an idea.
Basically i think you need the first available room_no to be assigned to your abc-xyz timespan. So, you should be fetching the first good value that is not in the already-booked set.
Example query could be something like this
select room_no
from
bookings
where
room_no not in (
select
room_no
from bookings
where start_time >= 'abc' and end_time <='xyz'
)
limit 1

check if it happens in 24 hours

Imagine we're giving users the ability to send emails using our website, but we want to limit them to not send more than 30 emails per day(24 hours).
So, by sending each email we're gonna insert a record into our table, then while he/she wants to send another one, we check if he has sent more than 30 emails during 24 hours or not.
How we could check this with PHP?
we query db, we got 20 records for this user, the date of records are:
2012-08-14 13:10:58
2012-08-14 12:45:47
2012-08-14 16:32:18
2012-08-14 19:10:40
...
...
...
How we could achieve such rule?
Thanks
Don't check it in PHP, use a simple query like this to get the answer out of he database right off the bat.
select
count(*)
from
yourTableName
where
dateCol>date_sub(now(), interval 1 day)
and userID=...
This will give you the count.
Edit: As Boris points out, this will count per day, you could change it to check for the last 24 hour period like this:
select
count(*)
from
yourTableName
where
dateCol>date_sub(now(), interval 24 hour)
and userID=...
Edit 2: After checking this, Riad correcly points out, these two do in fact return the same value. The 1 day is treated as exactly 1 day, not a calendar date. If the date column has a datetime of '2012-08-13: 13:00:00' a date_sub( dateCol, interval 1 day) will return '2012-08-12: 13:00:00'.

Getting an event from a database a week in advancee

I am currently developing a sports website where one of the pages with be forthcoming fixtures in which the user will be able to what team and where the team are playing their next match.
I have a database with the following fields...
ID
TEAM NUMBER
OPPOSITION
VENUE
DATE
MEET TIME
MATCH TYPE
So a row of data pulled from the DB and print_r'd may look like this
ID=>[1] TEAM NUMBER=>[1] OPPOSITION=>[YORKSHIRE] VENUE=>[HOME] DATE=>[2009/4/25] MEET TIME=>[13.00] MATCH TYPE=>[CUP]
My problem is i cannot work out how to show the next match dependent on what the current date is, so for example for now I want the site to show all the games that will happen over the weeken of the 25th April 2009 and then once that has gone the fixtures for the next weekend.
Hope this makes sense and some one give me an idea of how to tackle this.
select * from my_events where date between now() and date_add(now(), interval 7 day);
Should do it I think.
Instead of relying entirely on MySQL, you can also use PHP's strtotime() function:
$query = "select * from my_events where date between now() and ".
date("Y-m-d", strtotime("+1 week"));
For MySQL check out the Date and Time functions. You can use a combination of CURDATE() and ADDDATE() to achieve what you need.
Your description is very vage but try something like this:
SELECT all_fields_you_need
FROM table_name
WHERE `DATE` > CURDATE() AND `DATE` <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)
ORDER BY `DATE` ASC
(not tested, just written as it came into my mind...)
Load it all into an array and display the data
you can get the system date (in Oracle using sysdate) and then add to it, so look for all records where DATE = sysdate + 7. You may have to play with this a little, formatting the date so that sysdate + 7 returns a date without the time, but that is basically what you need.
EDIT:
If you want the event between now and a week from now (if games are only on the weekend, then this will return next weekend's games) do
DATE > sysdate AND DATE <= sysdate + 7
To get the next match for team xxx
SELECT *
FROM myTable
WHERE TEAM NUMBER = xxx
AND DATE = ( SELECT MIN(DATE)
FROM myTable
WHERE TEAM NUMBER = xxx
AND DATE > NOW() )
I suspect this is what you really want, if matches only take place at weekends (which seems to be an assumption from your question).
Today + 7 days is not the same as next weekend unless today happens to be the same day of the week as the match.

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