Jump to content

Recommended Posts

hey guys!

I have got the following timer to work and can output it in the php section of the code and at times, managed to get it updated into the database. However, I noticed that sometimes, it will update as 00:00:00 instead of the actual time itself. I also am not sure how to edit the code to make it count down....Should I store it as just time or timestamp in the database?

 

<?php

if (!isset($_POST['submit'])) {
    header("Location: index.php?timer2=error");
} else {

include_once 'includes/dbh.php';



$test = $_POST['timer'];



$userid = 'piano0011';




$sql = "UPDATE primerlevel_tests
        SET time_achieved = ?
        WHERE user_uid = ?
       ";

$stmt = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($stmt, $sql)) {
          echo 'SQL error';
        } else {
          mysqli_stmt_bind_param($stmt, "ss", $test, $userid);
          mysqli_stmt_execute($stmt);
        }



 }
?>







<!DOCTYPE html>
<html>
<head>
	<title></title>
	<link rel="stylesheet" type="text/css" href="stopwatch.css">
	<link rel="stylesheet" type="text/css" href="">
	<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
</head>
<body>
  <form action="" method="POST">
  <input type ="text" name="timer" id='test1' >
   <button type="submit" name="submit">Click here to submit result</button>
  <div class="container">
     <h1 class="title">Stopwatch</h1>
     <h1 id="timerLabel">00:20:00</h1>
      <h1 id="timerResult"></h1>
     <input type="button" value="START" class="myButton" onclick="start()" id="startBtn">
     <input type="button" value="STOP" class="myButton" onclick="stop()">
     <input type="button" value="RESET" class="myButton" onclick="reset()">

<input type="button" class="myButton" onclick="output()" value="output">


   
   </div>
</form>
   
   <script>
var status =0;
var time = 0;

function start() {
   status = 1;
   document.getElementById("startBtn").disabled = true;
   timer();
}

function stop() {
   status = 0;
   
}

function reset() {
   status = 0;
   time = 0;
   document.getElementById("startBtn").disabled = false;
   document.getElementById("timerLabel").innerHTML = "00:00:00";
}

function timer() {
   if (status == 1) {
       setTimeout(function() {
          time--;
          var min = Math.floor(time/100/60);
          var sec = Math.floor(time/100);
          var mSec = time % 100;

          if(min < 10) {
               min = "0" + min;
          }

          if (sec >= 60) {
             sec = sec % 60;
          }

          if (sec < 10) {
             sec = "0" + sec;

          }

          document.getElementById("timerLabel").innerHTML = min + ":" + sec + ":" + mSec;
          timer();
          
       }, 10);
   }


   
}

function output() {
 var x = document.getElementById('timerResult').innerHTML = document.getElementById('timerLabel').innerHTML;

 document.getElementById('test1').value = x;

}






    
   </script>

  

 

 </form>


   
</body>
</html>

 

Edited by piano0011
Link to comment
https://forums.phpfreaks.com/topic/307512-timer-not-updating-in-database-reliably/
Share on other sites

A lot of "generalized" info and not enough specifics.

1. What type of field is time_achieved right now?I am guessing it is a "time" field type. My guess is that the value that is getting passed to update that field is not properly formatted for that field type - therefore it defaults to 00:00:00. But, I also see you have some javascript to reset the value of a field to 00:00:00 - perhaps there is something calling that function onsubmit of the form.

2. You ask about how to do a countdown. Storing a time value will not work for that. Instead you should be storing a timestamp of when the countdown should end. Then you can calculate how much time is left. If a user submits 00:20:00 (for a 20 minute timer), then your logic should set a timestamp 20 minutes in the future.

Assuming the columns in your table are like this

CREATE TABLE `primerlevel_tests` (
  `user_uid` varchar(10) NOT NULL DEFAULT '',
  `time_achieved` time(2) DEFAULT NULL,        // seconds to 2 dec.places
  PRIMARY KEY (`user_uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

then this revised code should work for you

if ($_SERVER['REQUEST_METHOD']=='POST') {
    
    include("db_inc.php");                 //  USE YOR OWN
    $conn = myConnect('test');             //  CONNECT CODE
    
    $test = $_POST['timer'] ?? 0;
    $userid = 'piano0011';

    if ($test) {
        $sql = "INSERT INTO primerlevel_tests
                (time_achieved, user_uid)
                VALUES (?,?)
                ON DUPLICATE KEY UPDATE time_achieved = VALUES(time_achieved)
               ";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $test, $userid);
        $stmt->execute();
    }
} 
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="stopwatch.css">
    <link rel="stylesheet" type="text/css" href="">
    <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
<script type="text/javascript">
    var status =0;
    var time = 0;

    function start() {
       status = 1;
       document.getElementById("startBtn").disabled = true;
       timer();
    }

    function stop() {
       status = 0;
       
    }

    function reset() {
       status = 0;
       time = 0;
       document.getElementById("startBtn").disabled = false;
       document.getElementById("timerLabel").innerHTML = "00:00:00";
    }

    function timer() {
       if (status == 1) {
           setTimeout(function() {
              time++;
              var min = Math.floor(time/100/60);
              var sec = Math.floor(time/100);
              var mSec = time % 100;

              if(min < 10) {
                   min = "0" + min;
              }

              if (sec >= 60) {
                 sec = sec % 60;
              }

              if (sec < 10) {
                 sec = "0" + sec;
              }

              document.getElementById("timerResult").innerHTML = "00:" + min + ":" + sec + "." + mSec;
              timer();
              
           }, 10);
       }
    }

    function output() {
        var x = document.getElementById('timerResult').innerHTML;
        document.getElementById('test1').value = x;
    }
</script>
</head>
<body>
  <form action="" method="POST">
      <input type ="text" name="timer" id='test1' >
      <button type="submit" name="submit">Click here to submit result</button>
      <div class="container">
         <h1 class="title">Stopwatch</h1>
         <h1 id="timerResult">00:20:00</h1>
          
         <input type="button" value="START" class="myButton" onclick="start()" id="startBtn">
         <input type="button" value="STOP" class="myButton" onclick="stop()">
         <input type="button" value="RESET" class="myButton" onclick="reset()">
         <input type="button" class="myButton" onclick="output()" value="output">
      </div>
</form>
</body>
</html>

 

Thanks and I have been trying to learn more about how a countdown or up timer works and have the following code... There is a problem with my seconds and that it just keeps ticking over the 60 seconds mark instead of resetting back to 00

 

image.png.dbb3712e645f5002d767f414ccad05ff.png

 

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
    #output {
        width:100px;
        height: 20px;
        background-color: #CCC;
        border: 1px solid #999;
    }
</style> 
<script>
   var time = 0;
   var running = 0;

   function startPause() {
      if(running == 0) {
        running = 1;
          increment();
          document.getElementById("startPause").innerHTML = "Pause";
      } else {
           running = 0
           document.getElementById("startPause").innerHTML = "Resume";
      }

   }

   function reset() {
      running = 0;
      time = 0;
      document.getElementById("startPause").innerHTML = "Start";
      document.getElementById("output").innerHTML = "00:00:00";
   }

   function increment() {
         if (running == 1) {
      setTimeout(function() {
      time++;
      var mins = Math.floor(time/10/60);
      var secs = Math.floor(time/10);
  
      var tenths = time % 10;
      
      if (mins < 10) {
           mins = "0" + mins;
      }

      if (secs < 10) {
           secs = "0" + secs;
      }

      if (secs > 59) {
            secs = "0" + secs;
      }
      
     
      document.getElementById("output").innerHTML = mins + ":" + secs + ":" + "0" + tenths;
      increment();
   }, 100);
  }
}
</script>
</head>
<body>
<p id="output"></p>
<div id="controls">
    <button id="startPause" onclick="startPause()">Start</button>
    <button onclick="reset()">Reset</button>
</body>
</html>

that line means

  • If the value $_POST['timer'] has been set then set $test to that value, otherwise set it to a default value of 0 (RTFM)

After that It then checks that the value is non-zero before attempting to update the database.

Regarding database storage, it is a time value so it makes sense to store it as TIME type.

4 hours ago, piano0011 said:

So, I don't have to convert to seconds before storing it? I will give your code a try, just not sure why sometimes, it was storing it as 0

MySQL has a number of different settings and modes it can run in.   By default it is permissive of invalid date/time/datetime values and will accept entry but convert these invalid values to '0'.

In the case of a time value, for example, insert of a value like '60' or '113' or '2:62:22'  will not be converted in the way you might expect, and those values will be set to a time value of '00:00:00'.

I suspect that this is likely the reason you are finding zeros in certain entries.

I have been trying to find a suitable countdown timer and I might have found one here but there are a couple of problem. Whenever I press the start button, it will quicken the timer and when I tried to add a form attribute, the timer doesn't work anymore. Just disappeared from the screen. I am also having another issue where the buttons are not centered when I did margin 15% auto for the main div class. Here is the code: Do I need to add the buttons id in my CSS?

 

<?php

$timer = 60;


?>





<!DOCTYPE html>
<html>
<head>
	<title></title>
	<link rel="stylesheet" type="text/css" href="style.css">
	<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
</head>
<body>


<script>
   var timer = <?php echo $timer ?>;    // 1 minute timer.... 
   var min = 0;
   var sec = 0;

   function startTimer() {
   	   min = parseInt(timer/60);
   	   sec = parseInt(timer%60);

   	   if(timer<1) {
   	   	   document.write("You have to start again!");
   	   }

   	   document.getElementById("time").innerHTML = "<b>Time Left:  </b>" + min.toString() + ":" + sec.toString();
   	   timer--;
   	   setTimeout(function() {
          startTimer();
   	   }, 1000);
   }



     function stop() {
     	
     	alert("Thank you for completing the test. You finished the test at: " +  min.toString() + ":" + sec.toString());
     	 
         var result = document.getElementById('time').innerHTML;
         document.getElementById('input').value = result;
    //   window.location.href = "update.php";
     }



</script>
<div class="timer">
<h1>Welcome to Timertrone.</h1>
<br></br>


   <div class="timer_display"><center><b><span id="time" ...></span></center></b></div>


<form>
<input type="text" id="input">
<h1 id="buttons"></h1>
<button type="submit" name="start" onclick="startTimer()">Start</button>
<button type="submit" name="start" onclick="stop()">Stop</button>
</div>
</form>
</body>
</html>


This is the CSS code:

div.timer {
  margin: 15% auto;

}

 #buttons {

position: relative;
left: 200px;
}

div.timer_display {
   font-family: 'Lobster', cursive;
   font-size: 40px;
   color: blue;
   padding-top: 100px;
}

 

I have tweaked your code for you

<?php
    $timer = 60;                // starting time in seconds
?>
<style type="text/css">
    div.timer {
        text-align: center;
        margin: 15% auto;
    }
    #msg {
        color: red;
    }
</style>
<html>
<head>
<script type="text/javascript">
    var timer = <?php echo $timer ?>;    // 1 minute timer.... 
    var min = 0;
    var sec = 0;
    var active = 1;
    
    function startTimer() {
        if (active==0) return;
        
        if (timer == 0) timer = <?=$timer?> ;
        timer--;
        
        min = parseInt(timer/60);
        sec = parseInt(timer%60);
        
        
        if(timer < 1) {
            $timer = 0;
            min = 0;
            sec = 0;
            document.getElementById("msg").innerHTML = "You have to start again" ;
            document.getElementById("time").value = "00:00:00";
            active = 1;
            return;
        }
        else {
            if (min < 10) min = '0'+min;
            if (sec < 10) sec = '0'+sec;
            document.getElementById("msg").innerHTML = "" ;
            document.getElementById("time").value = "00:" + min.toString() + ":" + sec.toString();
        }

        setTimeout(function() {
        startTimer();
        }, 1000);
    }

    function stop() {
        if (min + sec > 0) {
            alert("Thank you for completing the test. You finished the test at: " +  min.toString() + ":" + sec.toString());
            document.form1.submit();  
            active = 0;
        }
    }

</script>
</head>
<body>
<div class="timer">
    <h1>Welcome to Timertrone.</h1>
    <br>
    <form name='form1' action='update.php' method="post">
        Time left: <input type="text" name="time" id="time" value="">
    </form>
    <span id="msg"></span>
    </br> 
    <button name="start" onclick="startTimer()">Start</button>
    <button name="stop" onclick="stop()">Stop</button>
</div>
</body>
</html>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.