0

How to write a sql query to find out that there are 2 days left before the current date. In php, this can be done via:

$res['end_date'] - time () < 86400 * 3;

How can I do the same after 1 sql query, well or better, only 2 days, if less so that it does not work out, well, if it works out, it's okay.

UPD:

It is necessary to compose a sql query that will select only those records that have 2 days left before the end_date expires

The type is int for the field end_date and is stored via the time () function in php.

Can't compose a WHERE clause.

GMB
  • 216,147
  • 25
  • 84
  • 135
FixiDens
  • 29
  • 7

4 Answers4

0

You can use the FROM_UNIXTIME function to convert it to a DateTime you can then use the NOW() plus 2 days to check if the date is under 2 days. You then have to check that the date is before the current time otherwise you'll get dates that have already gone.

SELECT
    end_date
FROM 
    table
WHERE 
    FROM_UNIXTIME(end_date) <= NOW() + INTERVAL 2 DAY
AND
    FROM_UNIXTIME(end_date) > NOW()
Zack
  • 101
  • 6
0

Assuming that you are storing an epoch timestamp (the number of seconds since January 1st, 1970), I would recommend:

select *
from mytable
where end_date >= unix_timestamp() and end_date < unix_timestamp() + 2 * 24 * 60 * 60

unix_timestamp() gives you the current epoch. You can use simple math to add two days to that.

The upside of this approach is that this does direct filtering against the store value, so this can take advantagae of an index on end_date - as opposed to converting the timestamp to a date, which requires converting the whole column before the filtering can happen. So this is much more efficient.

You can ajust the inequalities as you prefer. I used a half-open interval (inclusive on the lower bound and exclusive on the upper bound), which is a widely used approach.

GMB
  • 216,147
  • 25
  • 84
  • 135
0

I ended up doing this:

$time = time();
$params = $db->query("SELECT * FROM `params` WHERE (`end_date` - {$time}) < 86400 * 3");

And it worked.

FixiDens
  • 29
  • 7
0

I always do

select *
from mytable
where FROM_UNIXTIME(end_date) < NOW() + INTERVAL 2 DAY

This will get results where two days in the future is ahead of the end date ie, anything that will end within 2 days (or has already ended as I didn't add a check for that)

Edit: I see you can't use where If you cannot use where clause

select FROM_UNIXTIME(end_date) - INTERVAL 2 DAY as end_date 
from mytable

And then check in php if the result is before or after. This will show all results however

Corby Jurgens
  • 76
  • 1
  • 6