Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用上个月的PHP脚本_Php - Fatal编程技术网

使用上个月的PHP脚本

使用上个月的PHP脚本,php,Php,下面是一段代码,它是一个更大的例程的一部分,尽管我所需要的帮助是更改代码,使其使用上一个月,或者使用定义月份的功能 当它执行时,它会根据当前月份(即2月份)向MySQL添加数据,但我需要让它也为1月份添加一次数据 任何帮助都会很好 $now = new DateTime('now'); $thisYear = $now->format("Y"); $thisMonth = $now->format('m'); $bookingsSql = str_replace('{check_in

下面是一段代码,它是一个更大的例程的一部分,尽管我所需要的帮助是更改代码,使其使用上一个月,或者使用定义月份的功能

当它执行时,它会根据当前月份(即2月份)向MySQL添加数据,但我需要让它也为1月份添加一次数据

任何帮助都会很好

$now = new DateTime('now');
$thisYear = $now->format("Y");
$thisMonth = $now->format('m');
$bookingsSql = str_replace('{check_in_year}', $thisYear, $bookingsSql);
$bookingsSql = str_replace('{check_in_month}', $thisMonth, $bookingsSql);
$bookingsSql = str_replace('{check_out_year}', $thisYear, $bookingsSql);
$bookingsSql = str_replace('{check_out_month}', $thisMonth, $bookingsSql);
$bookingsSql = str_replace('{close_date_year}', $thisYear, $bookingsSql);
$bookingsSql = str_replace('{close_date_month}', $thisMonth, $bookingsSql);

创建DateTime对象时,可以指定last month作为参数

或者,您也可以使用更改您的日期

$myToday = new DateTime ();
$lastmonth = $myToday->sub (new DateInterval ('P1M'));
print "Last month: {$lastmonth->format("m")}\n";
// Output: Last month: 01

如果您愿意,还可以定义自己的日期。请参阅。

为什么要一次又一次地覆盖同一个变量?@ShankarDamodaran:看起来像是一个过于简单的模板系统。用year/date值替换一堆{foo}模板变量;to$now=新的日期时间“上个月”;记录将使用January?@user3308857创建。正如上个月的参数所建议的,DateTime对象将使用当前日期之前的月份创建。如果您在2月份运行脚本,那么您的记录将在1月份开始。如果您在8月份运行脚本,您的记录将在7月份开始。
$myToday = new DateTime ();
$lastmonth = $myToday->sub (new DateInterval ('P1M'));
print "Last month: {$lastmonth->format("m")}\n";
// Output: Last month: 01