Good Morning,

I am trying to run a mysql query to see if the field 'Date' is within 7 days of the current date or not. If it is less than 7 days old, I want to echo an image called current.jpg. If it is more than 7 days old, I want to echo an image called notcurrent.jpg. I have been close but still cant seem to get it....Any help would be appreciated.

     <?php

    $Now = time(); 
    $Lastweek = time() - (7 * 24 * 60 * 60);



    if($row['Date']<= $Lastweek) {
    echo "<img src='/images/current.jpg' width='80' height='75'><br>";
    } else if ($row['Date'] > $Lastweek) {
    echo "<img src='/images/notcurrent.jpg' width='80' height='75'><br>";
    }

    ?>

Dani AI

Generated

got a working PHP-side check in the thread. Below are a couple of safer, production-ready alternatives and quick troubleshooting notes that address common gaps: database-side filtering for performance, PHP DateTime for timezone-safe comparisons, and things to watch for when the stored value is DATETIME vs TIMESTAMP.

For large result sets, push the logic into MySQL so the server can use an index and return only the rows that matter. Example SQL (adjust UTC_TIMESTAMP() vs NOW() to match how dates are stored):

SELECT id, `Date`,
  CASE WHEN `Date` >= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 7 DAY)
       THEN '/images/current.jpg'
       ELSE '/images/notcurrent.jpg'
  END AS icon
FROM items
WHERE `Date` IS NOT NULL;

When handling the check in PHP, prefer DateTime with an explicit timezone and a cloned threshold so the reference moment is unambiguous:

$tz = new DateTimeZone('UTC');
$now = new DateTime('now', $tz);
$threshold = (clone $now)->sub(new DateInterval('P7D'));
$d = DateTime::createFromFormat('Y-m-d H:i:s', $row['Date'], $tz);

if ($d && $d >= $threshold) {
    // show current image
} else {
    // show not-current image
}

Additional notes and pitfalls: follow 's point about using built-in date handling to avoid subtle time arithmetic bugs; prefer ISO-8601 datetime strings in the DB; be explicit about timezones (TIMESTAMP is timezone-converted by MySQL, DATETIME is not); avoid wrapping the date column in functions in WHERE clauses (that blocks index use); handle nulls and invalid strings before comparing; clarify whether "within 7 days" is inclusive or exclusive and pick >= vs > accordingly.

I got it to work...

if (strtotime($row['Date']) >= strtotime('-7 days')) {
echo "<img src='/images/current.jpg' width='80' height='75'><br>";
} else {
echo "<img src='/images/notcurrent.jpg' width='80' height='75'><br>";
}
Member Avatar for Member #120589

Just a point. strtotime relative dates is far better than using "seconds calculations" as they take into account daylight saving and leap years.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.