我想开发一个页面,用于存储数据库中页面消耗的总时间,当我再次登录同一页面时,时间在我存储在数据库中的旧时间之后开始计数。我是新的到PHP我开发了一些不起作用的代码,请帮忙!
<?php
$s=0;
$m=0;
$h=0;
while(true)
{
if($s==60)
{
$s=0;
if($m==60)
{
$m=0;
$h++;
}
else
{
$m++;
}
}
else
{
$s++;
}
sleep(1);
echo $h." ".$m." ".$s." ";
}
?>
这是我试过的请帮助!
答案 0 :(得分:1)
您需要进行如下设置:
Javascript
部分类似于:
<!-- let's say this is a sample page 'page_id.html' -->
<html>
<head>
<!-- include JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<!-- your page goes here-->
<!-- then at the END -->
<script>
// set the user ID
var USER_ID = "user_1";
// set the id of the page in the database
var PAGE_ID = "page_id.html";
// set the timer accuracy - ex. 5 seconds
var TIMER_ACCURACY = 5000;
// create the counter function
(function(UI, PID, TA){
// cal the PHP file every x seconds
var I = setInterval(function(){
// use AJAX so the page doesn't need to reload
$.ajax({
method:"post",
url:"ajax.php", // this is the link to the PHP file
data:{call:"counter", user_id: UI, page_id:PID}
})
.fail() // put some code here if server is unreachable
.done(); // put some code here to check server response
}, TA);
})(USER_ID, PAGE_ID, TIMER_ACCURACY);
</script>
</body>
PHP
部分:
<?php
// page "ajax.php"
// check $_POST data -> see if there is a call for "counter"
if (isset($_POST["call"]) && $_POST["call"] == "counter" && isset($_POST["user_id"]) && isset($_POST["page_id"])) {
// if there is, retrieve user_id & page_id
// filter $_POST data before using it into database
// ex. user only Alphanumeric chars and . _ -
$user_id = preg_replace("/[^A-Za-z0-9_.-]/", "", $_POST["user_id"]);
$page_id = preg_replace("/[^A-Za-z0-9_.-]/", "", $_POST["page_id"]);
// create an appropriate SQL query to UPDATE the counter for the HTML page with the user ID = $user_id page ID = $page_id
$sql = "UPDATE.... WHERE ....";
// run the query, update the counter
// if all ok
echo "1";
exit;
}
// if something goes wrong
echo "0";
exit;
?>
要在每个页面上包含Javascript部分,您应该设置一个模板,用于呈现包含脚本的HTML页面,并回显正确的PAGE_ID,如:
<?php
$user_id = "user_id"; // user identifier in the database
$page_id = "page_id.html"; // page identifier in the database
?>
<html>
...
<script>
// set the id of the page in the database
var USER_ID = "<?php echo $user_id.html; ?>";
var PAGE_ID = "<?php echo $page_id.html; ?>";
...