我缺乏一些PHP/MySQL环境的经验。我有一个名为MyTable的MySQL表。在其中,我有一个名为RowTime的字段,类型为DATETIME NOT NULL。在 PHP 中选择行后,我想检查 RowTime 是早还是小于 3 天。
鉴于所有不同类型的时间类型,有人可以帮助完成以下代码(我故意省略了各种错误处理):
$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];
// NEED HELP HERE to check whether $rowTime is older or younger than 3 days
mysqli_free_result($result);
您可以使用特殊的 SQL 运算符来检查您的日期是否超过 3 天:
$dblink = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$dbquery = "SELECT RowTime, IF(RowTime + INTERVAL 3 DAYS > now(), true, false) as isYounger FROM MyTable WHERE Id='" . $myId . "'";
$result = mysqli_query($dblink, $dbquery);
$numrows = mysqli_num_rows($result);
// ... Verify $numrows == 1 ...
$myRow = mysqli_fetch_assoc($result);
$rowTime = $myRow['RowTime'];
if($myRow['isYounger']) {
//record is younger
} else {
//record is older
}
mysqli_free_result($result);
您可以使用以下查询:
SELECT RowTime,TIMEDIFF(NOW(),RowTime)>"72:00:00" AS "Old" FROM MyTable ;
这将引入"旧"列,如果 RowTime 超过 3 天,则该列将为 1。否则将为 0。请注意,这不考虑时区。