php - 将日期时间 sql 值更新一年
问题描述
我试图获取一个日期时间变量(例如:2019-02-10 03:13:33)来准确更新一年。我读到日期时间被写成一个字符串,所以我试图自己减去并加上 +365。
如果我取出包括绑定值在内的所有“过期日期”,代码就可以工作。也出于某种原因,我必须将我的更新放在单引号中,因为如果它们在双引号内,我的数据库中没有任何变化。
$stmt = $db->prepare('UPDATE usr_customer_profile SET packageid = 3, expirationdate = .'$oneyear'. WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $_SESSION['expirationdate'], PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();
解决方案
您可以在 PHP 或 SQL 中执行此操作。在 PHP 中,您可以使用strtotime
或(最好)DateTime
该类将一年的值添加到$_SESSION['expirationdate']
:
// using strtotime
$expirationdate = date('Y-m-d H:i:s', strtotime($_SESSION['expirationdate'] . ' + 1 year'));
// using DateTime
$expiration = new DateTime($_SESSION['expiration_date']);
$expiration->add(new DateInterval('P1Y'));
$expirationdate = $expiration->format('Y-m-d H:i:s');
// do the query
$stmt = $db->prepare('UPDATE usr_customer_profile
SET packageid = 3,
expirationdate = :expirationdate
WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $expirationdate, PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();
在 SQL 中使用+ INTERVAL 1 YEAR
将 1 年添加到到期日期:
$stmt = $db->prepare('UPDATE usr_customer_profile
SET packageid = 3,
expirationdate = :expirationdate + INTERVAL 1 YEAR
WHERE usrcustomerid = :usrcustomerid');
$stmt->bindValue(':expirationdate', $_SESSION['expirationdate'], PDO::PARAM_STR);
$stmt->bindValue(':usrcustomerid', $_SESSION['usrcustomerid'], PDO::PARAM_INT);
$oneyear = (':expirationdate' - ':expirationdate') + 365;
$stmt->execute();
推荐阅读
- nestjs - 我可以在 Nestjs OpenAPI 中进行多态响应吗?
- ios - 如何使用 CMake 获取 iOS appex 文件
- python - 为什么我的回归线低于所有回归点?
- css - 创建这个 CSS 选择器的正确方法是什么?
- javascript - 引用分配给 getElementById 的变量时收到错误
- firebase - 关于 Firebase 连接
- python - 如何在使用 matplotlib 中的 FuncAnimation 时为不同的帧设置固定范围的颜色条
- google-app-engine - 在 App Engine (Flex) 中哪里可以找到堆转储
- c++ - C++ 中的类命名空间是什么?
- machine-learning - Sklearn.linear_model.Lasso 返回 +0 和 -0 的系数?