仅显示php中确定持续时间内的数据

wkftcu5l  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(387)

我有一个页面显示存储在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>';
    }
}
2uluyalo

2uluyalo1#

你可以使用 where 条款和a date_add 函数直接在sql查询中应用此筛选器。只需添加 duration 天到了 date_of_post 值,并将其与 NOW() .
请注意,因为您正在存储 duration 值作为varchar而不是int,您需要 convert 将持续时间值设置为 signed int .
下面是一个例子,使用 date_add 扩展到更清楚地了解正在发生的事情。

select
    *
from
    posts
where
    date_add
    (
        date_of_post,
        INTERVAL convert(duration, SIGNED INT) DAY
    ) > NOW()

顺便说一句,您应该始终尝试在查询中过滤数据,而不是在php脚本中。不要只在脚本中选择整个表—让sql做尽可能多的工作。rdbms比php高效得多,而且您将节省大量开销(例如,通过网络发送的数据量,以及必须使用多少ram来存储php使用的结果等)。

相关问题