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

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

我的表单有两个文本框 ok

coupon ,startingdate,

在优惠券文本框中输入的数据,例如 501,502,503,504,505,506。 数据类型 - varchar

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

现在我需要的是如果我的优惠券文本框有 6 个值并且我select日期选择器中的当前日期然后它插入 6 个日期每个日期+1个月。

for ex - 我的文本框有 501,502,503,504,505,506 总共 6 个值。我 select 13-02-2015 在日期选择器中点击保存

然后它创建 6 个日期,如下所示,并插入优惠券日期列。

请建议如何执行此操作...

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);