2017-08-09 10 views
0

私は入札システムに取り組んでいます。私は00:00に達すると、データベースから読み取り、メッセージを表示するタイマーを持っています。今、私はそれが< = 10secs(:00:00:00 10)になるようにタイマーを操作すると、ボタンがクリックされ、それが戻って00にリセットする必要があります:00:00:10と続けます。タイマーの表示は日、時、分、秒です。 はここでここJavaScriptコードphpのボタンを使ってカウントダウンタイマーを操作する方法は?

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); 

でPHPコードここ

<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> 

は、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;?> 

私は、PHPの初心者だの表示のためのコードです...数週間前にそれを学んだばかりです。あなたの時間は非常に高く評価されています。

+0

は私の答えを助け、あなたをしましたか? – Mcsky

答えて

0

私はあなたのスタートを支援することをwroted。私は現在、開発中の環境ではありませんので、このコードを実行しませんでした。 すべてのphpファイルを同じディレクトリに入れて通信する必要があります。

このファイルは、必要に応じてデータベースとの通信を可能にします。さらに、SQLインジェクションを避けるためにデータベースを要求する際には、PDOを使用することをお勧めします。

PHPのマニュアルを参照してください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; 
} 

あなたは扱う入札の作成を、このPHPファイル

このファイルに提出するの説明を入力したHTMLのPOSTフォームを実装する必要が

// 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 

この第3のファイルは、データベースにある入札の更新を処理します。

// 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 

あなたはいくつかのチュートリアルは、PHPとMySQLを学ぶ行う必要があり、あなたはそれが開始時より困難であるPHPフレームワークを使用する場合、それはまたあなたにたくさん:) をお手伝いしますが、その後、あなたはたくさん読んで、コードを学びます。そしてフレームワークは、 "良い習慣"にとどまるのを助けます。PHPで非常に簡単なコードを作るのは簡単です。 は、私は非常に多くの構文または論理エラーませんでした願っていますが、私は私の英語のため申し訳ありません を必要に応じて、stackoverflowのコミュニティが私を修正することを知っています! アンアップ票をいただければ幸いです:)

+0

申し訳ありません。私はここで本当にあなたのポイントを得ていません。特定のボタンがクリックされたときにリセットするタイマーを意味しますか?とにかく私は上記の方法なしでそれを行うことができますか?方法はちょっと混乱していて、私はPHPで音がないです。 – epospiky

+0

PHPで何をしたいですか? 更新bid.closing_date欄のボタンをクリック! 現時点でPHPコードは – Mcsky

+0

まさにダイナミックではありません。ボタンをクリックしたときにclosing_dateを更新したい私のPHPについては動的ではない。とにかく私はそれをダイナミックにすることができますか? – epospiky

関連する問題