Solved

Multiple Flexible Countdown Timers needed.

Posted on 2011-09-22
18
800 Views
Last Modified: 2012-05-12
I have a timer that works very well if I'm only pulling one record from the database and tie it to the timer.  The problem is, now my company would like to have multiple timers for a particular area in the plant.  I want to modify my original script to accomodate that.  

How can I change this script to encounter multiple database records?
<?php
require_once('db.php');


$query = mysql_query("SELECT * FROM jos_a_timer_east order by id DESC limit 1");


?>

<?php
while($row = mysql_fetch_array($query)) {

$recordid = $row['id'];
$timeh = $row['timeh'];
$timem = $row['timem'];
$times = $row['times'];
$date = $row['date'];
$batchNum = $row['batchNum'];
$date1 = explode("-", $date);
$query2 = mysql_query ("SELECT workCenter FROM jos_a_q0165_startup where batchNum = $batchNum");

while($row2 = mysql_fetch_array($query2)) {
	
$workCenter = $row2['workCenter'];
}


//Remove timer if End of Shift was filled out...for batchNumber
$query3 = mysql_query("SELECT batchNum FROM jos_a_q0165eos");
while($row = mysql_fetch_array($query3))
{
$batchNumEOS = $row['batchNum'];
if ($batchNum == $batchNumEOS) {
$query4 = mysql_query ("DELETE FROM jos_a_timer_east where batchNum = $batchNum");
while($rows=mysql_fetch_array($query4))
{
//Nothing here on purpose...	
}
} else {
}
}
$datey = $date1[0];
//Fixes month needing to be off by 1 month per notes below
$datem = $date1[1]-1;

$dated = $date1[2];
$temp2 = $datey. "," . $datem . "," . $dated. "," .$timeh ."," . $timem . "," . $times;
?>
<script type="text/javascript">
//######################################################################################
// Author: ricocheting.com
// Version: v2.0
// Date: 2011-03-31
// Description: displays the amount of time until the "dateFuture" entered below.

// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture1 = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture1 = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm

dateFuture1 = new Date(<?php print $temp2;?>);

// TESTING: comment out the line below to print out the "dateFuture" for testing purposes
//document.write(dateFuture +"<br />");


//###################################
//nothing beyond this point
function GetCount(ddate,iid){

	dateNow = new Date();	//grab current date
	amount = ddate.getTime() - dateNow.getTime();	//calc milliseconds between dates
	delete dateNow;

	// if time is already past
	if(amount < 0){
		document.getElementById(iid).innerHTML="Now!";
	}
	// else date is still good
	else{
		mins=0;secs=0;out="";

		amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

		mins=Math.floor(amount/60);//minutes
		amount=amount%60;

		secs=Math.floor(amount);//seconds

		if(mins != 0){out += (mins<=9?'0':'')+mins +" "+((mins==1)?"mins":"mins")+", ";}
		if(secs != 0){out += (secs<=9?'0':'')+secs +" "+((secs==1)?"secs":"secs")+", ";}
		out = out.substr(0,out.length-2);
		document.getElementById(iid).innerHTML=out;

		setTimeout(function(){GetCount(ddate,iid)}, 1000);
	}
}

window.onload=function(){
	GetCount(dateFuture1, 'countbox1');
	//you can add additional countdowns here (just make sure you create dateFuture2 and countbox2 etc for each)
};
</script>

<table class="timer">
	<tbody>

		<tr onClick="parent.location='index.php?option=com_breezingforms&view=form&Itemid=133'">
			<td class="timerspan"><div align="center">Work Center: <?php print $workCenter;?></div><div align="center">Next Report Due:</div><b><div style="color: #000; font-style:italic" align="center" id="countbox1"></div></b><div align="center">Click to fill out hourly report.</div></td>
		</tr>
<!--
<tr>
	<td><?php print $temp2;?></td>
</tr>
-->        	
</tbody>
</table>



<?php } ?>

Open in new window


I know I can change line #5 to this:

$query = mysql_query("SELECT * FROM jos_a_timer_east");

to allow for all of the records in the table to come back, but I can't get the JavaScript and PHP to work together properly for multiple instances...I can get the multiple tables to appear, but the countdown section just changes from one table to another as if the JavaScript code isn't recognizing that I am trying to pull mutliple records.

I tried doing this, but it didn't work: (additions are lines: 6, 48, 49. Modifications are lines: 102, 111)

 
<?php
require_once('db.php');


$query = mysql_query("SELECT * FROM jos_a_timer_east order by id DESC limit 1");
$i = 0;

?>

<?php
while($row = mysql_fetch_array($query)) {

$recordid = $row['id'];
$timeh = $row['timeh'];
$timem = $row['timem'];
$times = $row['times'];
$date = $row['date'];
$batchNum = $row['batchNum'];
$date1 = explode("-", $date);
$query2 = mysql_query ("SELECT workCenter FROM jos_a_q0165_startup where batchNum = $batchNum");

while($row2 = mysql_fetch_array($query2)) {
	
$workCenter = $row2['workCenter'];
}


//Remove timer if End of Shift was filled out...for batchNumber
$query3 = mysql_query("SELECT batchNum FROM jos_a_q0165eos");
while($row = mysql_fetch_array($query3))
{
$batchNumEOS = $row['batchNum'];
if ($batchNum == $batchNumEOS) {
$query4 = mysql_query ("DELETE FROM jos_a_timer_east where batchNum = $batchNum");
while($rows=mysql_fetch_array($query4))
{
//Nothing here on purpose...	
}
} else {
}
}
$datey = $date1[0];
//Fixes month needing to be off by 1 month per notes below
$datem = $date1[1]-1;

$dated = $date1[2];
$temp2 = $datey. "," . $datem . "," . $dated. "," .$timeh ."," . $timem . "," . $times;
$test = $i.'test';
$i++;
?>
<script type="text/javascript">
//######################################################################################
// Author: ricocheting.com
// Version: v2.0
// Date: 2011-03-31
// Description: displays the amount of time until the "dateFuture" entered below.

// NOTE: the month entered must be one less than current month. ie; 0=January, 11=December
// NOTE: the hour is in 24 hour format. 0=12am, 15=3pm etc
// format: dateFuture1 = new Date(year,month-1,day,hour,min,sec)
// example: dateFuture1 = new Date(2003,03,26,14,15,00) = April 26, 2003 - 2:15:00 pm

dateFuture1 = new Date(<?php print $temp2;?>);

// TESTING: comment out the line below to print out the "dateFuture" for testing purposes
//document.write(dateFuture +"<br />");


//###################################
//nothing beyond this point
function GetCount(ddate,iid){

	dateNow = new Date();	//grab current date
	amount = ddate.getTime() - dateNow.getTime();	//calc milliseconds between dates
	delete dateNow;

	// if time is already past
	if(amount < 0){
		document.getElementById(iid).innerHTML="Now!";
	}
	// else date is still good
	else{
		mins=0;secs=0;out="";

		amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

		mins=Math.floor(amount/60);//minutes
		amount=amount%60;

		secs=Math.floor(amount);//seconds

		if(mins != 0){out += (mins<=9?'0':'')+mins +" "+((mins==1)?"mins":"mins")+", ";}
		if(secs != 0){out += (secs<=9?'0':'')+secs +" "+((secs==1)?"secs":"secs")+", ";}
		out = out.substr(0,out.length-2);
		document.getElementById(iid).innerHTML=out;

		setTimeout(function(){GetCount(ddate,iid)}, 1000);
	}
}

window.onload=function(){
	GetCount(dateFuture1, '<?php print $test;?>');
	//you can add additional countdowns here (just make sure you create dateFuture2 and countbox2 etc for each)
};
</script>

<table class="timer">
	<tbody>

		<tr onClick="parent.location='index.php?option=com_breezingforms&view=form&Itemid=133'">
			<td class="timerspan"><div align="center">Work Center: <?php print $workCenter;?></div><div align="center">Next Report Due:</div><b><div style="color: #000; font-style:italic" align="center" id="<?php print $test;?>"></div></b><div align="center">Click to fill out hourly report.</div></td>
		</tr>
<!--
<tr>
	<td><?php print $temp2;?></td>
</tr>
-->        	
</tbody>
</table>



<?php } ?>

Open in new window


Anyone have ideas of what I am doing wrong?
0
Comment
Question by:NUKIT
  • 12
  • 6
18 Comments
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
I noticed in the second script it shows I didn't change line 5.  Even changing this to:

 
$query = mysql_query("SELECT * FROM jos_a_timer_east");

Open in new window


doesn't do anything, but add a table per record in the database.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
It almost looks like you have a data base table with multiple columns carrying pieces of the DATETIME values.  If that is the case, you might want to use a new strategy for carrying that kind of information.  This article will tell you how it's done.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

IIRC there are some java-script and PHP interaction examples that might be helpful.
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Thanks I'll check it out and get back to you.
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Ray, thanks for the article, but unless I'm wrong, none of that will help with a timer that is working without reloading the page.  I can get something like this to work without JavaScript, but we don't want to have to reload the page to see how much time has passed.  With the timer I integrated PHP with JavaScript and am able to get it to count down the the future time and date I placed in the database table.

I just need to figure out how to get multiple rows within the table to be populated with the time counting down (integrated with JavaScript)

I have an idea, it came ot me as I was heading to school today, that I will try tomorrow morning at work.

Thanks
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Ok, so I've narrowed it down to this piece being the hurdle for what I need:
window.onload=function(){
	GetCount(dateFuture1, 'countbox1');
	//you can add additional countdowns here (just make sure you create dateFuture2 and countbox2 etc for each)
};

Open in new window


I need to be able to write the additional:

GetCount(dateFuture2, 'countbox2');

statements on the fly based on how many rows are in the database.  I am getting the number of rows using this query:

$num_rows = mysql_num_rows($query);

But since this is a window.onload parameter, it only loads once...I'm not sure I will be able to accomplish what I need to do unless I rewrite the entire logic of of the page.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Hmm.. I think having multiple different countdown timers on the same page would be possible.  Not sure I understand the part about the data base back end.  But let's start with this and see what we get.  You can test it on my server here.
http://www.laprbass.com/RAY_countdown_timer.php
<?php // RAY_countdown_timer.php
error_reporting(E_ALL);
?>

<script type="text/javascript">
var interval = "";
var sekonds  = 10;

function startInterval()
{
    interval = window.setInterval("tTimer()",1000);
}
function stopInterval()
{
    window.clearInterval (interval);
    interval="";
}
function tTimer()
{
    document.thinkTime.tDisplay.value = sekonds--;
    if (sekonds == -1)
    {
        stopInterval();
    }
}
</script>

<script>
document.write('<meta http-equiv=\"Refresh\" content=\"10;url=http://lmgtfy.com?q=JavaScript+Timer\">');
</script>

<form name="thinkTime">
This page will search for a JavaScript Timer in
<input readonly class="timerBox" size="1" type="text" name="tDisplay" value="">
<script>startInterval();</script>
seconds.
</form>
<a href="http://lmgtfy.com?q=JavaScript+Timer">Click here if you don't want to wait.</a>

Open in new window

0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
I don't see how that's in any way relevant to my needs...

I already know how to create a single countdown timer.

I am going to delete this question as I am just going to change the logic of the pages to match that of this:

http://www.w3schools.com/php/php_ajax_database.asp
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
I've requested that this question be deleted for the following reason:

I am going to change the logic of the page to match:<br /><a href="http://www.w3schools.com/php/php_ajax_database.asp" target="_blank">http://www.w3schools.com/p<wbr />hp/php_aja<wbr />x_database<wbr />.asp</a><br /><br />I need to focus on display 1 timer at a time based on selection of select list.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Good luck.  I think you are going to need it.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Wow, very unprofessional Ray.  This is supposed to be a forum where we help each other.  I see how your posts are trying to help, but posting something about searching for Google on this matter doesn't help as I've done my reasearch, but figured there is someone out there who can assist me much faster if they have something they have already created.

"Good luck. I think you are going to need it."  not classy man...
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
You might consider giving us a little time to try to work out a solution for you.  As the old adage goes, "haste makes waste" and sometimes I do not have time to do the job right in a single sitting.  In those cases, I am not willing to give you a sloppy answer or do the job wrong.  And if you don't really want a tested and working answer, why ask the questions?  We are unpaid volunteers here, y'know?

You have a few moving parts to your question.  One is how to put multiple timers on the page.  I just finished the example that shows how I can do that.  Another part of this question is how to get information from PHP into the Javascript.  The example shows that, too.  Another part of the question is how to get the information from your data base into PHP variables.  I don't have your data base, so you're on your own for that part of it.  However I do know that a data base table with multiple columns carrying pieces of the DATETIME values is not a technically competent design.  I recommend that you redesign that table.  If you learn about the ISO-8601 date/time format you will save yourself a lot of headaches, going forward.

Here is why I think you are going to need luck with this application.  If you make repeated AJAX requests to update a timer, you will be doing N* the amount of work on the server, where N is the number of seconds in the timer value.  However if you read the data base once and send the javascript timer values to the client machine, the timing will continue in front of the client and you will not need those repeated requests.  If you get a lot of clients, all making repeated AJAX requests,... Well, I hope you get the idea!
<?php // RAY_temp_nukit.php
error_reporting(E_ALL);

// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_27322730.html

// SET THE TIMER VALUES
$thinkTime = 5;
$otherTime = 7;
?>

<script type="text/javascript">
var interval = "";
var sekonds  = <?php echo $thinkTime; ?>;
var seconds  = <?php echo $otherTime; ?>;

function startInterval()
{
    interval = window.setInterval("tTimer()",1000);
}
function stopInterval()
{
    window.clearInterval (interval);
    interval="";
}
function tTimer()
{
    document.thinkTime.tDisplay.value = sekonds--;
    document.otherTime.tDisplay.value = seconds--;

    if (sekonds == -1)
    {
        stopInterval();
    }
}
</script>

<script>
document.write('<meta http-equiv=\"Refresh\" content=\"<?php echo $thinkTime; ?>;url=http://lmgtfy.com?q=JavaScript+Timer\">');
</script>

<form name="thinkTime">
This page will search for a JavaScript Timer in
<input readonly class="timerBox" size="1" type="text" name="tDisplay" value="">
<script>startInterval();</script>
seconds.
</form>
<a href="http://lmgtfy.com?q=JavaScript+Timer">Click here if you don't want to wait.</a>
<br/>
<form name="otherTime">
This timer value starts at <?php echo $otherTime; ?> and is currently
<input readonly class="timerBox" size="1" type="text" name="tDisplay" value="">
seconds.
</form>

Open in new window

0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Ray,

I understand the time concept of working on something, but if you are going to work on something and then get back to me with it, just put that down instead of a link to google to do a search for it.

Also, the database values, I understand your point.  The database design is not mine, I'm working with a database developer who designed that...clunky, but I don't have a choice, I get to work with what I have.

Lastly, I'm not asking how to get PHP to talk to JavaScript or vice-versa, I'm not asking how to get information from the database into PHP or into JavaScript, I already know how to do all of that...what my question was stating is that I need to extend the currently working timer script to include mutliple timers on the fly...

I will try your script and get back to you.
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Ray,

Can you extend your script to include minutes?

I need minutes, not just seconds.

Thanks
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I believe that JS timers run in thousandths of seconds.  See line 18 above.
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Thanks.
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
Thanks
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Thanks for the points.  It's a good enough question that I think I might write an article about it, as soon as I can get a generalized example together.  All the best, ~Ray
0
 
LVL 13

Author Comment

by:NUKIT
Comment Utility
And it might be worth the time integrating it with a database as well...I'm sure I'm not the only one out there that needs this kind of functionality.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now