Okay, so I do understand that if I am running the strtotime function on a day that is the 29th or higher I will incur the February bug and get a result for March instead.
Also I get that if I set the date to Feb 1st, I can avoid the issue.
But here is the problem. I am rolling through the last 12 months of records to generate sales/billing numbers for tracking. How do I ask for all records in February when my loop looks like this?
setlocale( LC_MONETARY, 'en_US' );
$i = 0;
while( $i <= 11 ) {
$select = "SELECT * FROM `my_table` " .
"WHERE YEAR( billing_date ) = '" . date( 'Y', strtotime( -$i . ' month' )) . "' " .
" AND MONTH( billing_date ) = '" . date( 'm', strtotime( -$i . ' month' )) . "'";
$result = mysql_query( $select );
$num_rows = mysql_num_rows( $result );
$sales = 16 * $num_rows;
echo "<p align='center'>";
echo "Sales for " . date( 'M, Y', strtotime( '-' . $i . ' month' ) ) .
" " . money_format( '%i', $sales );
echo "</p>";
$i++;
}
How do I avoid the February bug? Would it be an if
statement? What would that look like?
Here is a pure SQL solution (if I correctly understand the scenario):
SELECT
YEAR(billing_date) AS billing_year,
MONTH(billing_date) AS billing_month,
16 * COUNT(*) AS sales /* Why x16?!!! */
FROM my_table
GROUP BY YEAR(billing_date), MONTH(billing_date)
This will calculate the sales directly in SQL, so in PHP you just need a display loop.
How do I ask for all records in February...
SELECT * FROM table
WHERE MONTH(billing_date) = 2
February bug? It's not a bug. Normalizing dates is a (useful) feature! :-)
If you want the last day in February, ask for the 0th of March.
I don't know the "february bug", but you could try to use MySQL to subtract 1 month. Check
SELECT DATE_SUB(billing_date, INTERVAL 1 MONTH) FROM my_table
=> Manual
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.