简体   繁体   English

如何使用此方法遍历mysql数据库表

[英]How can I use this method to loop through a mysql database table

How can I use this method to loop through a mysql database table and display a timer for each record in the table based on a date/time stored in one of the fields? 如何使用此方法遍历mysql数据库表并根据存储在其中一个字段中的日期/时间为表中的每个记录显示计时器?

$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$Row = (mysqli_fetch_assoc($result));
$th = $Row['endtime'];    
}



var today = new Date();
var DD = today.getDate();
var MM = today.getMonth()+1; //January is 0!
var YYYY = today.getFullYear();
//let get the Difference in Sec btw the two dates
var _DateFromDBProgEndDate = '<?php echo $th; ?>';
var ProgEndTime = new Date(_DateFromDBProgEndDate);
var TodayTime = new Date();

var differenceTravel = ProgEndTime.getTime()- TodayTime.getTime() ;
var seconds = Math.floor((differenceTravel) / (1000));
////////////////////////////////
var SecDiffFromToday = seconds;
var seconds = SecDiffFromToday;
function timer() {
    var days        = Math.floor(seconds/24/60/60);
    var hoursLeft   = Math.floor((seconds) - (days*86400));
    var hours       = Math.floor(hoursLeft/3600);
    var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
    var minutes     = Math.floor(minutesLeft/60);
    var remainingSeconds = seconds % 60;
    if (remainingSeconds < 10) {
        remainingSeconds = "0" + remainingSeconds; 
    }
    document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(countdownTimer);
        document.getElementById('countdown').innerHTML = "Completed";
    } else {
        seconds--;
    }
}
var countdownTimer = setInterval('timer()', 1000);

and this is my javascript 这是我的javascript

Here is a possible solution. 这是一个可能的解决方案。 It collects the dates from the database in an array: 它以数组的形式从数据库中收集日期:

PHP 的PHP

<?php
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
$th = [];
while ($row = mysqli_fetch_assoc($result)) {
    $th[] = "'" . date('U', $row['endtime']) . "'";
}
?>

Then in the part where you generate the javascript , you use this $th variable to populate an javascript array: 然后在生成javascript的部分中,使用此$th变量填充javascript数组:

var _DateFromDBProgEndDate = [<?=implode(",", $th)?>];

The javascript part then continues as follows: 然后, javascript部分将继续如下:

Javascript Java脚本

function pad(n) {
   // utility function to pad a number to 2 digits:
   return ('0' + n).substr(-2); 
}

function timer() {
    var todaySeconds = Math.floor(new Date().getTime() / 1000);
    // collect the html first in an array
    var html = [];
    // keep track whether there are still counters not yet zero:
    var allDone = true;
    // go through the list of dates:
    endDatesInSeconds.forEach(function (endDateSeconds) {
        var totalSeconds = endDateSeconds - todaySeconds;
        var days        = Math.floor(totalSeconds/24/60/60);
        var seconds     = Math.floor(totalSeconds - days*86400);
        var hours       = Math.floor(seconds/3600);
        seconds         = Math.floor(seconds - hours*3600);
        var minutes     = Math.floor(seconds/60);
        seconds         = seconds % 60;
        // add a part of html
        html.push(
            totalSeconds <= 0 
               ? 'Completed'
               : days + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds));
        // when at least one counter is not complete, we are not done:
        allDone = allDone && totalSeconds <= 0;
    });
    // now put the html in the document:
    document.getElementById('countdown').innerHTML = html.join('<br/>');
    if (allDone) {
        clearInterval(countdownTimer);
    }
}
var countdownTimer = setInterval('timer()', 250);

Here is a fiddle , which does not have the php part, but uses four dummy times to work with. 这是一个小提琴 ,它没有php部分,但是使用了四个虚拟时间来工作。

A few notes about your original code: 有关原始代码的一些注意事项:

  • it is dangerous to test for seconds == 0 as there is no guarantee that the timer will tick exactly every second, and there is no guarantee that your times returned by the database are not already in the past. 测试seconds == 0很危险,因为不能保证计时器会精确地每秒滴答,也不能保证数据库返回的时间已经过去。 In both cases you could get negative seconds, and your timer would in fact never stop. 在这两种情况下,您都可能会得到负秒数,并且计时器实际上永远不会停止。
  • You decreased the seconds variable with one, but as it is not guaranteed that the timer will tick exactly every second, you will slip away from the actual time difference. 您将“ seconds变量减小了一个,但是由于不能保证计时器会精确地每秒滴答,因此您会偏离实际的时差。 Therefore it is better to always get the current time again, and calculate the difference again. 因此,最好总是再次获得当前时间,并再次计算差值。 I my answer I let the timer tick more often, to get more exact results. 我的回答是让计时器更频繁地计时,以获得更准确的结果。
  • You had some code to pad the seconds part with a leading zero, but you'll want that too for minutes and maybe hours. 您有一些代码将秒部分填充为前导零,但您也希望在几分钟甚至几小时内都这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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