开发者

PHP: Compare Date

I'm encountering the following problem:

I'd like to compare today's date against some dates in a database, then if it isn't expired yet, show something... but if all the dates in the table are expired, show something like 'No lecture scheduled at this time, return again'.

As for the first thing it's no problem, but I can't show the text where there aren't any future dates...

Here's the code,

Table: id, dateposted, date_course, title, body

$sql = "SELECT *
        FROM L
        ORDER BY L.dateposted DESC;";
        $result = mysql_query($sql) or die(mysql_error());
        while($row = mysql_fetch_assoc($result))
        {
            $exp_date = $row['date_course']; 
            $todays_date = date("Y-m-d"); 
           开发者_高级运维 $today = strtotime($todays_date); 
            $expiration_date = strtotime($exp_date); 
            if ($expiration_date >= $today)
            {
                echo "<a href='courses.php'>" . $row['title']. "</a>";
                echo "</br>";   
            }
        }


I'll assume you're using MySQL. A couple of small changes to your query and code should make this work. You should definitely do this kind of filtering in the query and not the code.

$sql = "SELECT *
    FROM L
    WHERE date_course < NOW() AND dateposted < NOW()
    ORDER BY L.dateposted DESC;";

$result = mysql_query($sql) or die(mysql_error());

if (mysql_num_rows($result) > 0)
{
    while ($row = mysql_fetch_assoc($result))
    {
        echo "<a href='courses.php'>" . $row['title']. "</a>";
        echo "</br>";
    }
}
else
{
    echo "No results available";
}


Several ways to do it. One would be to make the date comparison part of the query. If no rows are selected, show your special message.

Otherwise, you can set a flag like

$has_courses = false;
while ($row = fetch() {
   $has_courses = true;
   ...
}
if (!$has_courses) { echo 'No courses'; }


Although you could do this far more efficiently by improving your query, here is the specific fix you request:

$sql = "SELECT *
        FROM L
        ORDER BY L.dateposted DESC;";
        $result = mysql_query($sql) or die(mysql_error());
        $out = false;
        while($row = mysql_fetch_assoc($result))
        {
            $exp_date = $row['date_course']; 
            $todays_date = date("Y-m-d"); 
            $today = strtotime($todays_date); 
            $expiration_date = strtotime($exp_date); 
            if ($expiration_date >= $today)
            {
                $out = true;
                echo "<a href='courses.php'>" . $row['title']. "</a>";
                echo "</br>";   
            }
        }
        if (!$out)
          echo 'Nothing found.';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜