I'm making a site where users post text posts and each post has a countdown timer on, different for each one. I am having a problem where I am only able to have one timer running.
I have a function to get the time depending on the time in the database for the post and the current time. The php file loops through each post and calls the time function to get the time for each post. However it is only creating one timer.
code for the timer
function getTime($conn, $pid){
$countDownDate;
$sql = "SELECT * FROM userposts";
$result = mysqli_query($conn,$sql);
while ($row = $result->fetch_assoc()){
if ($row['pid'] == $pid){ // getting the row of the user
$countDownDate = $row['time'];
}
}
echo "<p style='color:black' id='demo'></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date('".$countDownDate."');
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id='demo'
document.getElementById('demo').innerHTML = days + 'd ' + hours + 'h '
+ minutes + 'm ' + seconds + 's ';
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById('demo').style.color = 'red';
document.getElementById('demo').style.fontWeight = '900';
document.getElementById('demo').innerHTML = 'EXPIRED';
}
}, 1000);
</script></br>";
}
code to get time in each post
function getPosts(){
while ($row = $result->fetch_assoc()){
echo "<div class='post-box'><p>";
// displaying time
getTime($conn,$row['pid']);
echo "</p></div>";
}
}
it is only displaying the time for the first post in the loop