php-pdo代码从所选日期计算下一个6个月的日期


php pdo code to calculate next 6 month date from selected date

我的表单有两个文本框,可以

coupon ,startingdate,

在优惠券文本框中输入的数据,如501502503504505506。数据类型-varchar

startingdate是一个日期选择器-数据类型-日期时间

现在我需要的是如果我的coupontextbox有6个值s,并且我在日期选择器中选择当前日期,那么它会在每个日期中插入6个日期,其中+1个月

例如-我的文本框共有501502503504505506个值。我在日期选择器中选择"2015年2月13日",然后单击"保存"

然后创建6个日期,如下所示,并插入coupondate列

plz建议如何做到这一点。。。

501-   13-03-2015,
502-   13-04-2015,
503-   13-05-2015,
504-   13-06-2015,
505-   13-07-2015  
506 -  13-08-2015

下面是我的代码

coupondate数据类型-varchar因为我们需要以逗号分解形式在同一列中插入所有日期值

<?php
if(isset($_POST['save']))
{
$coupon = $_POST['coupon']; 
$startingdate = $_POST['startingdate'];
$coupondate = date("d-m-Y", strtotime($startingdate) . " +1 month");
$insertrow = $database->insertRow("INSERT INTO receipt_entry (coupondate,coupon,startingdate)                       
VALUES  (:coupondate,:coupon,:startingdate)",                       
array(':coupondate'=>$coupondate,':coupon'=>$coupon,':startingdate'=>$startingdate))
}
?>
$coupon       = '501,502,503,504,505,506';
$startingdate = '13-02-2015';
// Replace:
//    $coupondate = date("d-m-Y", strtotime($startingdate) . " +1 month");
// with:
$coupons = explode(',', $coupon);
$dates = Array();
for ($no = 1; $no < count($coupons) + 1; $no++) {
    $dates[] = date("d-m-Y", strtotime($startingdate . " +" . $no . " MONTHS -1 DAYS"));
}
$coupondate = implode(',', $dates);
// Test output
echo $coupondate, PHP_EOL;

输出:

12-03-2015,12-04-2015,12-05-2015,12-06-2015,12-07-2015,12-08-2015

我会使用DateTime而不是时间函数。

$coupon       = '501,502,503,504,505,506';
$startingdate = DateTime::createFromFormat('d-m-Y', '13-02-2015');
$coupondate = clone $startingdate;
$coupons = explode(',', $coupon);
$interval = new DateInterval('P1M');
$params = array(
   ':coupon' => $coupon,
   // i assume this is an actual date column and will need to 
   // in SQL date format
   ':startingdate' => $startingdate->format('Y-m-d'),
   ':coupondate' => array()
);
foreach ($coupon as $k => $coupon) {
   // add 1 month to the previous coupondate
   $coupondate->add($interval);
   $params['coupon'][] = $coupondate->format('d-m-Y');       
}
// implode out dates to a comma sep list
$params[':coupondate'] = implode(',', $params[':coupondate']);
$database->insertRow("INSERT INTO receipt_entry (coupondate,coupon,startingdate) VALUES  (:coupondate,:coupon,:startingdate)", $params);