2014-03-26 76 views
1

开始我需要循环通过一年的2012年12月间的月至2017年十一月开始那么一个月就是12,结束月份是11,起始年是2012年,收官之年的2017年PHP循环遍历月,在十二月

然后我询问与日期格式的数据库为2014年3月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; 

}

您的帮助深表感谢。

+1

我发布了n个答案,然后意识到我不知道你实际上有什么问题。 –

+0

环路和做什么?无论如何,您可以将数据库中的日期截至一年。 – Jonast92

回答

6

你最大的问题是你从来没有真正执行查询。我也用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]; 
} 
+0

感谢约翰,你的解决方案正是我之后。循环遍历开始和结束限制的日期。我离开了数据库的mysql_query关闭,因为它最终是无关的刚通过的日期循环的问题。太棒了。 –