how to increase a static number automatically everyday using php - php

I use wordpress and I have static number for a field which is taken from sql query.
<p class="counter-number">843</p>
I would like to increase that number everyday. For example when the page is loaded default number is 843 next day it should show 844 the day after it should show 845.
How can I do this? I prefer PHP but if it is possible also can use jquery.

<?php
$now = time();
$your_date = strtotime("2010-01-01"); //Starting date
$datediff = floor(($now - $your_date)/(60*60*24));
?>
<p class="counter-number"><?=$datediff?></p>
Code taken from Finding the number of days between two dates
This way it will always show the difference from the starting date to now, in days.

jQuery Answer
You will have to setup the starting date for it to increase daily. The idea is to get the date difference and add it to that counter.
HTML
<p class="counter-number">843</p>
jQuery
jQuery(function() {
// Get Starting Number
var starting_number = parseInt(jQuery('.counter-number').text());
// Create Day difference (because it increases by 1 each day)
var preset_start_date = new Date("21/03/2015");
var current_date = new Date();
var timeDiff = Math.abs(current_date.getTime() - preset_start_date.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var final_counter = starting_number + diffDays;
jQuery('.counter-number').text(final_counter);
});
I haven't tested it. But this is an idea to get that done.

For your case here are two ways achieve the goal.
use php
//client site php_cnt.html
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>visit_cnt</title>
</head>
<script type="text/javascript"src="http://localhost/php_cnt.php">
</script>
</html>
//server site php_cnt.php
<?php
//Here is the some logic to process the visit count
$visit_cnt = 11; // assume read it from mysql
echo "document.write($visit_cnt);";
?>
use javascript/jquery
//client site php_cnt.html
$(function() {
$.get('http://localhost/php_cnt.php',{r:Math.random()},function(cnt) {
$('. counter-number').html(cnt);
});
});
//the server site code
<?php
//Here is the some logic to process the visit count
$visit_cnt = 11; // assume read it from mysql
echo visit_cnt;
?>
Hope this can help you !

Related

Reverse counter FlipClock with PHP-MySQL

I want to use flipclock for the reverse counter. The timer should start from hh:mm:ss (eg, 19:40:46) to 00:00:00.
Below is the code
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 1, 0, 1);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.dw_clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true,
showSeconds: true
});
});
I don't want the date. Also, the time values should get fetched from MySQL and are different for different users when they log in. From PHP-MySQL, I have:
function timeToPlay(&$smarty){
$sqlStr = "select timediff('24:00:00', time(taken_on)) as timeRemaining,
hour(timediff('24:00:00', time(taken_on))) as hour,
minute(timediff('24:00:00', time(taken_on))) as minute,
second(timediff('24:00:00', time(taken_on))) as second
FROM profile_sicc_exer_score where user_id=".$_SESSION['user_id']."
order by id desc limit 1";
$sqlQuery = mysql_query($sqlStr) or die(mysql_error()."<hr>".$sqlStr);
if ( mysql_num_rows($sqlQuery) ) {
$timeToPlayNext = mysql_fetch_assoc($sqlQuery);
$smarty->assign("timeRemaining",$timeToPlayNext['timeRemaining']);
$smarty->assign("hour",$timeToPlayNext['hour']);
$smarty->assign("minute",$timeToPlayNext['minute']);
$smarty->assign("second",$timeToPlayNext['second']);
}
}
From the above code, I get the values of (example)
$timeRemaining = 19:40:46
$hour = 19
$minute = 40
$second = 46
How do I use the values in the above Flipclock code which is javascript/jquery...
For flipClock, you have to change the clockFace to "HourlyCounter", so it doesn't show the date.
After that, having the php variables, you can "echo" them into the javascript code, for example, at the end of the webpage, you can put:
<script>
clock.setTime(<?php echo $hour*3600+$minute*60+$second; ?>);
</script>
You can always put it in an "onload" function or something like that, but it should work fine with that.
You didn't left any details about the actual html page where the counter is showing, so I can't help you further this.
Good luck!

Javascript timed loop with php

I'm trying to display the current timestamp and refresh every second, doing this with php is too slow and has to reload the page and I know javascript doesn't, I just don't know how to, any help?
<?php
$time = time() + 3600 * 15;
echo $time;
?>
<meta http-equiv="refresh" content="0.5;time.php" />
Thanks in advance.
JavaScript can call up a timestamp based on your local time. Use setInterval to loop and update the timestamp given by Date.now().
setInterval(function() {
document.getElementById("timestamp").innerHTML = Date.now();
}, 16);
See jsFiddle.

show and hide based on server date and time

So here's what I'm trying to do - I have the following code:
<div id="on">
<p>We are: <span class="onair">ON AIR</span></p>
</div>
<div id="off">
<p>We are: <span class="offair">OFF AIR</span></p>
</div>
And what I'd like to do is "show" the "on" div on Tuesday's from 3pm to 4pm (server time), while simultaneously hiding the "off" div - and then switch that around for every other date/time.
?
If you use PHP you can do logic statements on the server-side to render the exact information you need instead of calculating it later on the client side.
(Client side solutions work too if you dont care about where the time is coming from)
(1) You can have the server render javascript for you that you can use in a script
//if you want the server's time you can do this:
<?php $timestamp = time(); ?>
//render variables in javascript instead of html
<?php
echo <<<EOD
<script>
var timestamp = ${timestamp}
//then later in your javascript process the timestamp logic to update the dom
</script>
EOD;
?>
(2) You can also have the server render a className in the body tag based on whether or not a condition is true or false. (This is my preferred method usually)
//onAirClass( min, max, timestamp ) returns className
//this function returns onair or offair class if the timestamp is in range
function onAirClass( timeMin, timeMax, timestamp ){
if( timestamp >= timeMin && timestamp <= timeMax ){
return 'onair';
}
return 'offair'
}
//using onAirClass( min, max, timestamp )
<?php $bodyClass = $bodyClass . ' ' . onAirClass( $timestamp ); ?>
<?php echo "<body class='${bodyClass}'>"; ?>
then in your styles you can have the elements you want to hide or show based on class inheritance from the body tag.
Check out the PHP time function to create new time strings, and do time calculations for your onAirClass() function
How to check the time between a given time range
UPDATED
Corrected PHP syntax errors
#maerics solution is OK, depending on what you want to do, just don't EVER do anything like this:
var timestamp = $('#server-timestamp').text();
Ultimately, there are many ways to do the same thing, but some things are more 'right' than others.
There are reasons to do some calculations on the client side vs the server side, and vice versa. As a newbie developer, just make sure that whatever method you use:
is simple
is efficient (doesnt do anything unnecessary or redundant)
falls in line with best practices
Actually this can be accomplished using just JavaScript without any server-side code, by using your timezone offset.
Here's a function you can use:
var onAir = function (day, start, end, timezone) {
var local, utc, show, days, onAir, startValues, endValues, startTime, endTime, startMinutes, endMinutes, showMinutes;
// by default, we are not on air
onAir = false;
// map day numbers to indexes
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Firday', 'Saturday'];
// convert start/end times to date objects
startValues = start.split(':');
endValues = end.split(':');
startTime = new Date();
endTime = new Date();
startTime.setHours(startValues[0], startValues[1]);
endTime.setHours(endValues[0], endValues[1]);
// add the hours minutes together to get total minutes
startMinutes = (startTime.getHours() * 60) + startTime.getMinutes();
endMinutes = (endTime.getHours() * 60) + endTime.getMinutes();
// get the current local time
local = new Date();
// get the current time in the show's timezone
utc = local.getTime() + (local.getTimezoneOffset() * 60000);
show = new Date(utc + (3600000*timezone));
// convert the show hours + minutes to just minutes
showMinutes = (show.getHours() * 60) + show.getMinutes();
// test to see if the show is going on right now
if (days[show.getDay()] === day && (showMinutes >= startMinutes && showMinutes <= endMinutes)) {
onAir = true;
}
return onAir;
}
// example: Air time is Tuesday between 1-2pm Central Time (-6)
var texasShowOnAir = onAir('Tuesday', '13:00', '14:00', '-6'));
// now check if we are on air
if (texasShowOnAir) {
// do stuff here...
}
You can now use this function like this:
var check = onAir('DAY', 'STARTTIME', 'ENDTIME', 'YOURTIMEZONE');
This will return a true/false. Be sure and use 24 hour format.
I would even argue that this is better than using your server's timestamp, because often (especially if you have shared hosting), your server can be set in a different timezone than you.
Here's a demo fiddle: http://jsfiddle.net/stevenschobert/mv54B/
Have the server provide a timestamp when it generates the page and have the client also generate a timestamp when it loads the page so that you can calculate the time offset between the two systems.
Then you can call a function on some interval that checks the current server time to see if it is within the 3pm-4pm period and show/hide the target elements as needed.
From the server:
<div id="server-timestamp" style="display:none">2013-02-12T18:01:19Z</div>
On the client:
$(document).on('load', function() {
var serverTime = new Date($('#server-timestamp').text())
, clientTime = new Date()
, offsetMilliseconds = (clientTime - serverTime);
setInterval(function() {
// If server time is 3pm-4pm then hide/show divs...
}, 1000 /* every second */);
});

How to count time from when user load a page/form until they submit it?

I have a quiz page with some questions (multiple choice, true-false). In the results after the submit of page i want to show something like this:
Started on Tuesday, 1 January 2013, 04:09 AM
Completed on Tuesday, 1 January 2013, 04:10 AM
Time taken 47 secs
Grade 7 out of a maximum of 10 (65%)
i dont know how to count start time and end time to show the above results and how to count the time from when user's load a page until they submit the form.
i'm new and i need your advise. i dont have problem if the problem solved with php or javascript or jquery
You can do something like this and the start and end timestamps will be submitted along with the form. You could then do the calculations with PHP.
var form = document.getElementById("form");
window.onload = function() {
var start = document.createElement("input");
start.type = "hidden";
start.name = "start";
start.value = +new Date()/1000; //unix timestamp
form.appendChild(start);
};
form.onsubmit = function() {
var stop = document.createElement("input");
stop.type = "hidden";
stop.name = "stop";
stop.value = +new Date()/1000;
form.appendChild(stop);
};
Ok here is my solution:
1- user starts the quiz and you put the time in $_SESSION var
$_SESSION['quiztime']=date("Y-m-d H:i:s");
2-User finishes the test and you check the time passed (this example is in minutes you don't have to divide it by 60 if you need seconds)
$to_time = strtotime(date("Y-m-d H:i:s"));
$from_time = strtotime($_SESSION['quiztime']);
echo round(abs($to_time - $from_time) / 60,2). " minutes";
I'd put the time started in a cookie or session, and then once they complete it, just subtract that time from the current time -- That's the time taken!
It may look like this:
Quiz page:
session_start();
$_SESSION['startTime'] = time();
// This is where the quiz would be displayed
Quiz results page:
session_start();
$totalTime = time() - $_SESSION['startTime'];
echo $totalTime;
My "bullet-proofer" solution would be to store the start time on the server, (in the session) associated with a unique id generated per-form and kept in an hidden field.
This way you prevent the user from tampering with it (he might change the unique id, but in that case the form would be invalid) and you don't depend on the client having javascript enabled.
<?php
$form_uuid = uniqid();
$_SESSION['quiz_start_time'][$form_uuid] = time();
Then, in your form, put something like this:
<input type="hidden" name="form_id" value="<?php print $form_uuid; ?>">
And in the form submit handler:
<?php
$form_uuid = $_POST['form_id'];
if (!isset($_SESSION['quiz_start_time'][$form_uuid])) {
// The user is trying to do something nasty (or the session just expired)
// Return something like a 400 error
}
else {
$start_time = $_SESSION['quiz_start_time'][$form_uuid];
// Do other form processing here..
}

show dynamic time with javascript

I want to show the time which I have in my php variable with the help of Javascript
I am coding an online exam module, where I want to display the total elapsed time
say for example
$time_elapsed // contains the time taken till now from the start of the exam
And if I got a div say,
<div id="time"></div>
how can I show the dynamic running time with starting from $time_elapsed after load the window for each question
Please if you guys have an answer for this..
Thanks
hi you can use the following code for the purpose
the javascript will be:
var Timer;
var TotalSeconds,TotalMins, secs;
var elapsedtime ;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
elapsedtime = 0
time = Time
secs = TotalSeconds%60;
TotalMins = Math.floor(TotalSeconds/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if(TotalSeconds-elapsedtime>0)
{
elapsedtime += 1;
secs = (elapsedtime%60)-60;
TotalMins = Math.floor(elapsedtime/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
else
alert("time up")
}
function UpdateTimer() {
Timer.innerHTML = TotalMins + ":" + secs;
}
nw create a html div where you want to show the running time.
Html:
<div id='timer' />
<script type="text/javascript">window.onload = CreateTimer("timer", 5);</script>
give parameter the time limit. it will alert after time finishes.
and to get time after refresh of the page use html5's sessionStorage
visit Html5 Storage Doc to get more details. using this you can store intermediate values temporaryly/permanently locally and then access your values
for storing values for a session
sessionStorage.getItem('label')
sessionStorage.setItem('value', 'label')
or store values permanently using
localStorage.getItem('label')
localStorage.setItem('value', 'label')
So you can store (temporarily) form data between multiple pages using html5 storage objects
This is how to display dynamic time. To use other php based starting time replace the line time0 = new Date(); by time0 =<?php echo $startTime;?>; which should be in ms since the epoch.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>elapsed time demo</title>
<script type="text/javascript">
var time0;
function initTime() {
time0 = new Date();
window.setInterval("updateTime()", 1000);
}
function updateTime() {
var timeNow = new Date();
var deltas = (Number(timeNow) - Number(time0))/1000;
var deltah = ("0"+String(Math.round(deltas / 3600))).substr(-2);
deltah = deltah.substr(-2);
deltas %= 3600;
var deltam = ("0"+String(Math.round(deltas / 60))).substr(-2);
deltas = ("0"+String(Math.round(deltas % 60))).substr(-2);
document.getElementById("timedisplay").firstChild.data=deltah+":"+deltam+":"+deltas;
}
</script>
</head>
<body onload="initTime();">
<div> elapsed time <span id="timedisplay">00:00:00</span></div>
</body>
</html>​
Your php code should return the time elapsed at the point of loading the page, however, javascript will then take over and increment that time as time passes.
You can send the parameter to your JavaScript function which is display time
function display_time(int time)
{
//your code for further integration
}
You can send the parameter to JavaScript function using following way
//call the function at the time display time
display_time(<?php echo $time_elapsed ?>)

Categories