使用 php 仅显示确定持续时间的数据

Only show data for a determined duration with php

我有一个页面显示 posts 存储在 mysql 数据库中。创建 post 后,用户可以 select 他们希望 post 可见多长时间,我正在尝试计算如何只显示 post确定的持续时间。这是我的一些代码(希望能展示我正在尝试的逻辑)。

//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 子句和 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 脚本中。不要只是 select 你的整个 table 到你的脚本中 - 让 SQL 做尽可能多的工作。 RDBMS 比 PHP 高效得多,而且您会节省很多开销(例如,通过网络发送的数据量,以及必须使用多少 RAM 来存储 PHP 的结果)一起工作,等等)。