On Jun 9, 8:27*am, One <david.hun...@gmail.comwrote:
>
I want to do a SELECT based on a date range - but mySQL
syntax expects the month range to be two digits.
So I have converted the month to show the leading zero
like this :
$next_month = date('m')+1;
$this_month = date('m');
$pre_month = date('m')-1;
However this outputs :
6
06
5
Why does the leading zero get dropped when adding to
the date function ?
Because initially, date() returns a string "06". When you attempt to
add or subtract an integer from that value, it is converted to the
integer 6. The result of the computation is an integer as well.
Is there a better way to be doing this ?
Yes. Here's a possibility:
// Find out current time:
$ts = time();
// Find out what day of the month it is:
$day = date('d', $ts);
// Find out how many days there are in that month:
$days = date('t', $ts);
// Produce the date for the end of the next month:
$next_month = date('Y-m-t', $ts + ($days - $day + 5) * 24 * 60 * 60);
// Produce the date for the beginning of the previous month:
$pre_month = date('Y-m-01', $ts - ($day + 5) * 24 * 60 * 60);
// Create the query:
$query = 'select * from table where date_range is '
. "between ('{$pre_month}') and ('{$next_month}')";
Cheers,
NC