How do I create a countdown, and compare todays date/time with a date/time in a database?

Joined
Aug 22, 2025
Messages
12
Reaction score
0
Hello.

Just a quick query.
I'm trying to build/create a very basic auction element/expiry time.

I've got a date and time stored in a database, and what I'd like to do is:-
1. Check, is the date in the database table the same as today's date?
2. if so, countdown the hours, minutes, and seconds to zero.

What I've got so far, is very rough. at present load the database table into a html table (using php), and checked if the data in the database table/field is the same as today's date. If so, add the record into the html table.

I'm just a little stuck with creating the countdown, and using todays date and time and comparing it with the date/time in the database to create a countdown and to refresh the countdown to zero.

Could anyone please advise me?
Thank You.
 
Joined
Jan 13, 2025
Messages
29
Reaction score
7
PHP:
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "auction_db";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch auction data
$sql = "SELECT auction_id, auction_end_time FROM auctions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $auctionEndTime = new DateTime($row['auction_end_time']);
        $currentDateTime = new DateTime();

        // Check if the auction end time is today
        if ($auctionEndTime->format('Y-m-d') === $currentDateTime->format('Y-m-d')) {
            $remainingTime = $auctionEndTime->getTimestamp() - $currentDateTime->getTimestamp();

            if ($remainingTime > 0) {
                $hours = floor($remainingTime / 3600);
                $minutes = floor(($remainingTime % 3600) / 60);
                $seconds = $remainingTime % 60;

                echo "<div class='auction-timer'>";
                echo "<h3>Auction ID: " . $row['auction_id'] . "</h3>";
                echo "<p>Time remaining: " . sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds) . "</p>";
                echo "</div>";
            } else {
                echo "<div class='auction-timer'>";
                echo "<h3>Auction ID: " . $row['auction_id'] . "</h3>";
                echo "<p>Auction has expired.</p>";
                echo "</div>";
            }
        }
    }
} else {
    echo "No auctions found.";
}

$conn->close();
?>

There you go
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,471
Messages
2,571,822
Members
48,797
Latest member
PeterSimpson
Top