Jump to content

PHP Countdown timer


Alpha-Omega

Recommended Posts

Greetings, fellow members:Recently i've started learning PHP and SQL so i could design my own web page, and i've hit a roadblock when trying to figure out how to run a countdown timer.The general idea is:- User logs in (i have done that)- User sees his main personal page. There is a button to start a countdown, that will go on even after the user has logged out.My idea is that once the button, or the link has been pressed, the user will have one year to do whatever the page is about ( In this case, riddles)I've tried to use

$start_time = strtotime("now");$end_time = strtotime("today + 1 year");$time_left = $end_time - $start_time;echo "You have $time_left seconds left... <br />";

Which causes a correct output in seconds left (1 year in mind). However, as you can see my problem, is that $start_time and $end_time are updated according to the current date. SQL comes into work here. I can insert $start_time and $end_time into a table to get their fixed position when the user clicks the start button. However, if i do this, the timer won't be on a countdown. The substraction would always show the same value that was inserted in the tables.My question is. How would i approach about making a working timer that shows decreasing seconds, that is correctly assigned for each individual user? Example/Full codes would be very very much appreciated. I excuse myself, i am not expert at this yet, but i try to learn.

Link to comment
Share on other sites

Well, you'll have to retrieve the ending time from the database, convert it into a PHP date format, and then you obtain the Unix timestamp of it. You subtract it to the unix timestamp of the current date and you then have to convert the result back into months, days, hours, minutes and seconds.After that you'll have to give the date to javascript in a javascript date format and go subtracting the seconds to it.It's a hard job but not impossible. I'd have to spend pretty long working it out.

Link to comment
Share on other sites

Has no one ever observed that PHP's date('U') returns the same number as javascript's date.getTime()/1000 ? They're both based on the Unix epoch.This make timers very easy.(Yes, you need to cast Javascript's as an int. No big deal.)

Link to comment
Share on other sites

Thanks kindly for your replies. I have been wondering, what if i don't want JS on my pages?I've constructed this code:

//  First, let's check if the user has already started the timer.$started = mysql_query('SELECT started FROM `users` WHERE username = \'$username\' LIMIT 0, 30 ');if ($started == 1)	{		echo "You have already started the timer. You have time left.<br />";	} else {		// Let's configure the start and end dates.	$startTime = time();$endTime = strtotime(today + 1 year);	// Insert these values into the database.	$qry = mysql_query('UPDATE $table SET startTime = \'$startTime\' WHERE username = \'$username\'') or die("Could not insert data because "     mysql_error());$qry = mysql_query('UPDATE $table SET endTime = \'$endTime\' WHERE username = \'$username\'') or die("Could not insert data because "     mysql_error());	// Set the flag for the started timer.$qry = mysql_query('UPDATE $table SET started = \'1\' WHERE username = \'$username\'') or die("Could not insert data because "     mysql_error());	// Dates have been set.  Unsetting them...	unset($startTime,$endTime);	// Let the user know the start and finish date.echo "Solving Hoix is not enough. It has to be done before the time runs out..<br />";echo "You have one year from now on to finish";}

I know i am not an expert at forming code. If someone knows how to clean it up, or if it has mistakes, i would very much like it to be pointed. Anyway, what i thought of, was inserting the start time and end time to the database, and have them fixed. Then have another variable like "$currenttime = time();" compare itself to the endtime in the database, so a correct countdown can be issued. All times above are in Unix timestamp. Ideas?

Link to comment
Share on other sites

It will be best to store timestamps in the database, that way you can use integers for everything. You might not need to store the start time in the database, all you need to know is the expire time. Once you have the difference between the current time and end time in seconds, you can write that out to Javascript to have a countdown show up. PHP can't do a countdown on the page, if you want anything on the page to change without a refresh you need to use Javascript. If you want the timer to be PHP-only then you would need to refresh the page every second to get the current value.

<?php$secs_left = $db_end_time - time();?><div>Seconds Left: <span id="timer"><?php echo $secs_left; ?></span></div><script type="text/javascript">var secs_left = <?php echo $secs_left; ?>;var timer_interval = 0;function update_timer(){  document.getElementById("timer").innerHTML = --secs_left;  if (secs_left < 1)  {	clearInterval(timer_interval);	alert("done");  }}timer_interval = setInterval("update_timer()", 1000);</script>

Link to comment
Share on other sites

You can't update more then one table with a single query, but you can update more then one field of you separate the list of fields and values with a comma.UPDATE table SET field1=val1, field2=val2, field3=val3

Link to comment
Share on other sites

My code showed some error.This is the full code:

<?php if (!isset($_COOKIE['loggedin'])) die("You are not logged in!");  $username = $_COOKIE['mysite_username'];include("config.php"); // connect to the mysql server$link = mysql_connect($server, $db_user, $db_pass)or die ("Could not connect to mysql because ".mysql_error());// select the databasemysql_select_db($database)or die ("Could not select database because ".mysql_error());//  First, let's check if the user has already started the timer.$started = mysql_query('SELECT started FROM `users` WHERE username = \'$username\' LIMIT 0, 30 ');if ($started == 1)	{		echo "Hoix - Start <br />";	} else {		// Let's configure the start and end dates.	$startTime = time();$endTime = strtotime("today + 1 year");	// Insert these values into the database.	$qry = mysql_query("UPDATE $table SET startTime = \'$startTime\' WHERE username = \'$username\'") or die("Could not insert data because "     mysql_error());$qry = mysql_query("UPDATE $table SET endTime = \'$endTime\' WHERE username = \'$username\'") or die("Could not insert data because "     mysql_error());	// Set the flag for the started timer.$qry = mysql_query("UPDATE $table SET started = \'1\' WHERE username = \'$username\'") or die("Could not insert data because "     mysql_error());	// Dates have been set.  Unsetting them...	unset($startTime,$endTime);	// Let the user know the start and finish date.echo "Solving Hoix is not enough. It has to be done before the time runs out..<br />";echo "You have one year from now on to finish";}?><?php$secs_left = mysql_query("SELECT endTime FROM `users` WHERE username = \'$username\'");?><html><title> Hoix - <?php echo $username ?> </title><body bgcolor="#000000" background="back.jpg"><textarea name="notepad" cols="10" rows="10"></textarea><br /><br /><div>Seconds Left: <span id="timer"><?php echo $secs_left; ?></span></div><script type="text/javascript">var secs_left = <?php echo $secs_left; ?>;var timer_interval = 0;function update_timer(){  document.getElementById("timer").innerHTML = --secs_left;  if (secs_left < 1)  {    clearInterval(timer_interval);    alert("done");  }}timer_interval = setInterval("update_timer()", 1000);</script><a href="logout.php"> Log out. </a></body></html>

And i get this error:

Parse error: syntax error, unexpected T_STRING in /home/kn000040/public_html/hoix/hoix.php on line 31

Line 31:

$qry = mysql_query("UPDATE $table SET startTime = \'$startTime\' WHERE username = \'$username\'") or die("Could not insert data because "     mysql_error());

Any ideas? The syntax may not be correct after all.

Link to comment
Share on other sites

Thank you for your replies. The endtime and starttimes are inserted into the database properly, UNIX seconds. I have another problem however, with both the javascript and an IF.same code as above. The idea is to retrieve from the started column a value of 1 or 0, TRUE or FALSE if the timer has already been started. This flag is set to 1 when setting up the database the first time the user visits the page. On subsequent times, the IF will take care of stopping that code from happening.Now my problem is:When i run the SQL query on phpmyadmin:

SELECT started FROM users WHERE username = 'exampleusername'

The value returned is 1. TRUE because it was inserted on the first time.However, when i try to convert this to PHP, i use this to store that value on PHP:

$started = mysql_query("SELECT started FROM users WHERE username = '$username'");

And echo it to see it's value, i see:

 Resource id #3 

Any ideas?EDIT: I've solved it. I was browsing through tutorials and function references, to learn that the query alone only returned if it existed or not existed. I had to use another function (mysql_resul($qry,1)) to make it work. Now it's all up and running. Thanks again for your assistance, i could not have completed without it.

Link to comment
Share on other sites

Apologies to be bumping this topic. There's a problem with the Javascript portion that i can't seem to get sorted out.The part of the code is:

<?php$qry = mysql_query("SELECT endTime FROM users WHERE username = '$username'");$secs_left = mysql_result($qry,0);?><div class="text"><img src="void/seconds.png"> <span id="timer"><?php echo $secs_left; ?></span></div><script type="text/javascript">var secs_left = <?php echo $secs_left; ?>;var timer_interval = 0;function update_timer(){  document.getElementById("timer").innerHTML = --secs_left;  if (secs_left < 1)  {    clearInterval(timer_interval);    alert("done");  }}timer_interval = setInterval("update_timer()", 1000);</script>

I know by echoing $secs_left (which is the endtime, ultimately), that the value is fixed and correct. (In this case: 1239427127). I saved another value, which was the starttime, just for record purposes (in this case for that user the start time is 1207891127). Now the idea is to have 1 year only in the timer. If i compare these two values (/60/60/24), i'd get 365, which is the year i want. However, i am not sure how the javascript works, but it appears like it's just resting seconds to the end time alone. (1239427127), and that makes a lot of years. How can i fix the javascript? Thanks in advance!

Link to comment
Share on other sites

I think what you really need to do is change your php.

$qry = mysql_query("SELECT endTime FROM users WHERE username = '$username'");$endtime = mysql_result($qry,0);$now = date("U");$secs_left = $endtime - $now;#Which means that this statement will still work just fine:var secs_left = <?php echo $secs_left; ?>;

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...