假设我有一个文本框,用户可以在其中输入日期(或者可以是现在使用 PHP 的当前日期的值)和一个"保存"按钮以执行一些操作将数据保存到我的数据库使其简单。
但在保存数据之前,我想执行此操作。
-
首先检查上个月是否已过去
-
如果上个月已过,则对新月份执行一些操作,或者否则,当您仍在本月时执行其他操作
这是我到目前为止所做的:
<?php
$currentDate = $_POST['date_input'];
# Get the previous month
$sql1 = "SELECT SUBDATE('$currentDate', INTERVAL 1 MONTH) AS prevMonth";
$result1 = mysql_query($sql1);
while($row1 = mysql_fetch_array($result1)) {
$prevMonth = $row1['prevMonth'];
}
# Compare previous date from the current date
$sql2 = "SELECT DATE('$prevMonth') < DATE('$currentDate') AS compareDate";
$result2 = mysql_query($sql2);
while($row2 = mysql_fetch_array($result2)) {
$result_date = $row2['compareDate'];
}
if($result_date == 1) { if TRUE
# This is the new Month
# Perform some action in this new month
}
else {
# Your still in this Month
# Cannot perform this else since the result_date is always TRUE
} ?>
假设当前日期是"2015-01-11"(2015 年 1 月 11 日)
上个月是"2014-12-11"(2014 年 12 月 11 日),条件 的 $result_date 将导致 1,因为 2014-12-11 <2015-01-11 为 TRUE。
但我的问题是,当我还在本月时,它不会触发 else 语句 因为将上个月的日期与当前月份的日期进行比较的结果将始终 当然,使用上面的查询是正确的。
我如何改进该代码以检查我是否仍在本月,然后执行一些 行动?有人可以帮助我吗?谢谢
你为什么要使用 MySQL?这是没有道理的。MySQL是一个数据库。
你可以用PHP来做。
<?php
$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P1M'));
echo $date->format('Y-m-d');
?>
有关详细信息,请参阅:http://php.net/manual/de/datetime.sub.php