PHP date minus X days

mysql, php

I have this code in PHP:

date('Y-m-d', strtotime("-7 days"))

which i am using in an SQL Query:

$sql="SELECT * from billing_invoices WHERE due_date <= '".date('Y-m-d', strtotime("-7 days"))."' AND (status = 'Unpaid' or status = 'Part Paid') AND statement = '0000-00-00 00:00:00' group by customer_sequence ";

so if the date is 2014-12-16 it will show 2014-12-09

i want to be able to run this Query too:

$sql="SELECT * from billing_invoices WHERE due_date <= '".date($_POST["date"], strtotime("-7 days"))."' AND (status = 'Unpaid' or status = 'Part Paid') AND statement = '0000-00-00 00:00:00' group by customer_sequence ";

but the date being returned is the current day rather than -7 days from the POSTED date

Best Solution

According to the PHP Manual for strtotime there is a second parameter where you can specify a timestamp wich is then used instead of the current time

int strtotime ( string $time [, int $now ] )

So your code should look like this:

date("Y-m-d", strtotime("-7 days", $_POST["date"]))

Perhaps you have to convert your date to a timestamp before. Dependent on your date format in $_POST["date"] this may work:

date("Y-m-d", strtotime("-7 days", strtotime($_POST["date"])))