【发布时间】:2019-01-02 15:19:27
【问题描述】:
我有一个页面显示存储在 mysql 数据库中的帖子。创建帖子后,用户可以选择他们希望帖子可见多长时间,我试图弄清楚如何仅在确定的时间内显示帖子。这是我的一些代码(希望能显示我正在尝试的逻辑)。
//Query database
$sql = <<<SQL
SELECT *
FROM `posts`
SQL;
if(!$result = $db_connection->query($sql)){
die('There was an error running the query [' . $db_connection->error . ']');
}
while($row = $result->fetch_assoc()){
//The date the post was made
$date_of_post = $row['date_of_post'];
//The duration of the post in days eg 7.
$duration = $row['duration'];
//Attempting to add duration to date
$newdate = strtotime($duration, $date_of_post);
//Only show posts that are still valid, eg date + duration is less than today's date
if($newdate > now()){
echo '<h2>Post Title</h2>';
echo '<p>Date of Posted:'.$date.'</p>';
}
}
【问题讨论】:
-
创建帖子后,用户可以选择他们希望帖子可见的时间那么您如何存储这些信息
-
使用
WHERE子句。 -
一些合理的代码缩进是个好主意。它可以帮助我们阅读代码,更重要的是,它将帮助 您调试代码 Take a quick look at a coding standard 为您自己谋福利。您可能会被要求在几周/几个月内修改此代码,最后您会感谢我的。
-
这是你的第一个错误,我希望它是你的第一个。将日期存储在 DATE 或 DATETIME 或 TIMESTAMP 列类型中,然后您可以轻松地在查询中使用它们
-
提示:使用
date_add将duration(转换为int)添加到date_of_post,并将其与NOW()进行比较。