简体   繁体   中英

how do i manipulate a countdown timer using button in php?

I'm working on a bidding system. I have the timer to read from the database and display a message when it reaches 00:00. Now i want to manipulate the timer in such a way that when it is <= 10secs(00:00:00:10), and a button is clicked then it should reset back to 00:00:00:10 and continue. The timer display is in day, hour, minute, and seconds. Here is the javascript code

function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
 s = "0" + s;
 return "<b>" + s + "</b>";
}

function CountBack(secs) {
  if (secs < 0) {
   document.getElementById("cntdwn").innerHTML = FinishMessage;
 return;
  }
  DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
  DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
  DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
  DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));

  document.getElementById("cntdwn").innerHTML = DisplayStr;
  if (CountActive)
   setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}

function putspan(backcolor, forecolor) {
 document.write("<span id='cntdwn' style='background-color:" + backcolor + 
            "; color:" + forecolor + "'></span>");
 }

 if (typeof(BackColor)=="undefined")
  BackColor = "white";
 if (typeof(ForeColor)=="undefined")
 ForeColor= "black";
 if (typeof(TargetDate)=="undefined")
 TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
 DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
CountActive = true;
if (typeof(FinishMessage)=="undefined")
 FinishMessage = "";
 if (typeof(CountStepper)!="number")
 CountStepper = -1;
 if (typeof(LeadingZero)=="undefined")
  LeadingZero = true;


CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
 CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);

Here is the php code

<body>
<?php
$mysqli = new mysqli("localhost","root","", "auction");
if (!$mysqli)
{
die('Could not connect: ' . mysql_error());
}

else{

 $sql = "INSERT INTO bids (id, description, closing_date) VALUES
(NULL, 'Acer Aspire 4736', '2011-10-22 18:50:26')";

}


$result = $mysqli->query("SELECT * FROM bids WHERE id = 1");

$row = mysqli_num_rows($result);

if ($row == 0)
{
die('No record found.');
}

$row = $result->fetch_array();
echo "Description: " . $row[1] . "<br />";
$closedate = date_format(date_create($row[2]), 'm/d/Y H:i:s');
echo "Closing Date: " . $closedate;
?>
<p>Time Left:
</p>
<script language="JavaScript">
TargetDate = "<?php echo $closedate ?>";
BackColor = "blue";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
FinishMessage = "Bidding closed!";
</script>
<script language="JavaScript" src="countdown.js"></script>
</body>

here is the code for the display in html

<?php
        $A=0;
        if ($A%4 ==0):;?>
        <?php
        while ($auction=$result->fetch_assoc()):;?>
        <div class = "grid ">
            <h4 class="c-head"><?=$auction['item_name']?></h4>
            <img src='<?=$auction['item_image']?>'  class="img-responsive">
            <span  class="timer">
                <script language="JavaScript">
                    TargetDate = "<?php echo $closedate ?>";
                    BackColor = "";
                    ForeColor = "";
                    CountActive = true;
                    CountStepper = -1;
                    LeadingZero = true;
                    DisplayFormat = "%%D%%, %%H%%:%%M%%:%%S%%";
                    FinishMessage = "Bidding closed!";
                </script>
                <script language="JavaScript" src="countdown\countdown.js">
</script>

            </span>
            <div class="input-group"> 
                    <span class="input-group-addon">$</span> 
                    <input type="digit" class="form-control" 
name="duration"> 
                    <span class="input-group-btn "><button class="btn btn-
primary c-button" type="button" name="bid">Bid now!</button></span>
            </div>

        </div>

<?php  endwhile; $A++; endif;?>

I'm novice in php...just started learning it a couple of weeks ago. Your time is greatly appreciated.

I wroted that to help your start. I haven't currently a dev environment under hands so I didn't run this code,. All the php files have to be put in the same directory to communicate

This file when required should allow you to communicate with your database. Moreover I used PDO that is good practice when requesting database to avoid SQL injections.

Please check the php documentation http://php.net/manual/fr/class.pdo.php

// database_connection.php
$host = 'localhost';
$user = 'root'; // Bad idea to user root user ^^'
$password = 'yourpassword';
$dbname = 'auction';

try {
    $dsn = sprintf('mysql:host=%s;dbname=%s', $host, $dbname);
    $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; // I active errors, if you are a beginner that'll help you, comment this in prod env
    // I use PDO to avoid SQL injections, this line open a mysql connection, check the documentation
    $connection = new PDO($dsn, $user, $password, $pdo_options);
} catch (PDOException $e) {
    echo 'Connexion failed : ' . $e->getMessage();
    exit;
}

You have to implement a HTML POST form with a description input which will submit to this PHP file

This file handle the creation of a bid

// addBid.php
// You have to implement a HTLM POST form with the needed fields which will submit to this PHP file
// The url yourdomain.fr/addBid.php
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
    if(!is_int($statusCode)) {
        // The error code isnt an integer
        throw new \Exception('error code isn\'nt an integer!');
    }

    if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
        throw new \Exception('invalid error code !');
    }

    header('Location: ' . $url, true, $statusCode);
    exit;
}

$description = isset($_POST['description']) ? $_POST['description'] : null;
$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended description isn't valid
if(empty($description) || !is_string($description)) {
    redirectTo($urlListing);
}

// You should do some verification on the string that send the user, it can be malicious html/javascript code, XSS attack

// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'INSERT INTO bids(description, closing_date) VALUES(":description", ":closing_date")';
$statement = $connection->prepare($sql);
$success = $statement->execute([
    ':closing_date' => $stringDate,
    ':description' => $description
]);
if(!$success) {
    echo 'The sql query didnt work as excepted';
    exit;
}

$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the bid is created
$urlListing .= '?created=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page

This third file handle the update of bid that is in the database

// updateBid.php
// The url yourdomain.fr/updateBid.php?bidId=6 will update the bid with id 6 into database
require 'database_connection.php';
function redirectTo($url, $statusCode = 301) {
    if(!is_int($statusCode)) {
        // The error code isnt an integer
        throw new \Exception('error code isn\'nt an integer!');
    }

    if(!in_array($statusCode, [301, 302, 307, 308])) { // 301, 302, 307, 308 are the valid http code for client redirect response
        throw new \Exception('invalid error code !');
    }

    header('Location: ' . $url, true, $statusCode);
    exit;
}

$bidId = isset($_GET['bidId']) ? $_GET['bidId'] : null;

$urlListing = 'yourdomain.fr/yourlistingurl';
// The sended bidId isn't valid
if(empty($bidId) || !is_numeric($bidId)) {
    redirectTo($urlListing);
}

// Start logic update
$inTenMinutes = new \DateTime('+10 minutes'); // I create a datetime object that represent the future in ten minutes
$stringDate = $inTenMinutes->format('Y-m-d H:i:s');
$sql = 'UPDATE bids SET closing_date = ":dateToModify" WHERE id = :id';
$statement = $connection->prepare($sql);
$success = $statement->execute([
    ':closing_date' => $stringDate,
    ':id' => $bidId
]);
if(!$success) {
    echo 'The sql query didnt work as excepted';
    exit;
}

$numberModifiedLines = $statement->rowCount(); // will return 0 or 1, it should return 1 if the $bidId is present in database
$urlListing .= '?updated=' . $numberModifiedLines;
redirectTo($urlListing); // All its ok, we redirect the browser to the listing page

You should do some tutorials learn PHP and MYSQL, that'll help you a lot :) Moreover when you use a PHP framework it is more difficult at the start but after that you'll learn a lot reading code. And the framework help you to stay in the "good practices", it very easy in php to do some shit code. I hope I didn't so many syntax or logic error but I know that the stackoverflow community will correct me if needed Sorry for my english !! An up vote would be greatly appreciated :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM