我需要遍历 2012 年 12 月到 2017 年 11 月之间的一年中的月份。所以开始月份是 12,结束月份是 11,开始年份是 2012,结束年份是 2017。
然后我查询日期格式为 2014-03-27 00:00:00 的数据库
我知道大约 4 年前我做过这种事情,但现在似乎无法解决。 这是我拥有的:
$year_start = 2012;
$year_end = 2017;
$month_start = 12;
$month_end = 11;
$year = $year_start;
$month = $month_start;
$number_of_months = 3;
if ($month < 13 && $year < $year_end ) {
$between_year_month = $year.'-'.$month;
//echo $between_year_month;
$query_total = "SELECT SUM(sales_points) FROM sales_list
WHERE user_id ='".$_SESSION['users_id']."'
AND sales_date BETWEEN '".$between_year_month."-01 00:00:00' AND '".$between_year_month."-30 23:59:59'";
echo $query_total;
$month++;
if($month == 13) {
$month = 1;
$year = $year + 1;
}
$between_year_month = $year.'-'.$month;
//echo $between_year_month;
非常感谢您的帮助。
最佳答案
您最大的问题是您从未真正执行过您的查询。我还使用 DateTime()
简化了循环, DateInterval()
, 和 DatePeriod()
.
$start = new DateTime('2012-12-01');
$end = new DateTime('2017-11-01');
$interval = new DateInterval('P1M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
$first_of_month = $dt->modify('first day of this month')->format('Y-m-d H:i:s');
$end_of_month = $dt->modify('last day of this month')->format('Y-m-d H:i:s');
$query_total = "SELECT SUM(sales_points) FROM sales_list
WHERE user_id ='".$_SESSION['users_id']."'
AND sales_date BETWEEN '".$first_of_month ."'
AND '".$end_of_month ."'";
$result = mysqli_query($query_total, $conn);
$row = mysqli_fetch_row($result);
echo $row[0];
}
关于PHP循环几个月,从12月开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22675345/