我想知道如何更改我的代码,以便在存在多个页面时为每个页面计算页面视图,并为每个页面显示正确的页面视图。
以下是我的php代码。
//Adds one to the counter
$mysqli = new mysqli("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"UPDATE counter SET counter = counter + 1");
//Retreives the current count
$count = mysqli_fetch_row(mysqli_query($mysqli,"SELECT counter FROM counter"));
if (!$dbc)
{
// There was an error...do something about it here...
print mysqli_error();
}
这是我的MySQL代码。
CREATE TABLE `counter` ( `counter` INT( 20 ) NOT NULL );
INSERT INTO counter VALUES (0);
这是我之前的替补表。
CREATE TABLE `counter` (
`id` int(11) NOT NULL auto_increment,
`ip` varchar(15) NOT NULL default '',
`page` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`),
KEY `ip` (`ip`,`page`)
)
这是我的旧页面计数器,我正在尝试与我的新页面计数器结合使用。
//Get the viewer's IP Address and the page he / she is viewing
$ip = $_SERVER['REMOTE_ADDR'];
$page = $_SERVER['PHP_SELF'];
//Check that the IP is not already listed for the current page
$viewer_check_query = "SELECT * FROM counter WHERE ip = '$ip' AND page = '$page'";
$viewer_check_result = mysql_query($viewer_check_query);
$viewer_check_numrows = mysql_num_rows($viewer_check_result);
//If numrows is equal to zero, then the user is new
if($viewer_check_numrows == 0){
//Add the new entry
$viewer_new_query = "INSERT INTO counter (ip, page) VALUES
('$ip', '$page')";
$viewer_new_result = mysql_query($viewer_new_query);
}
//Get the total number of viewers for this page
$viewer_total_query = "SELECT * FROM counter WHERE page = '$page'";
$viewer_total_result = mysql_query($viewer_total_query);
$viewer_total_numrows = mysql_num_rows($viewer_total_result);
答案 0 :(得分:3)
我不建议您“直播”更新数据库。而是使用mod_log_mysql或解析Apache日志文件“离线”。
为什么不呢?您可能想知道,如果有一天您有很多访问者,页面加载会停止,直到数据库更新为止。或者,如果数据库负载过重,更新将停止加载网页。
还有一个提示,使用jQuery或javascript为您的apache日志编写一个特殊的“logevent”,这样您就不会记录所有爬虫等。我正在使用以下代码:
function logger() {
var currenturl = location.href;
$.get("/logthis", { url: currenturl } );
}
$(document).ready(function(){
logger();
});
答案 1 :(得分:1)
您需要添加一个字段“path”,其中包含您网页的路径。
CREATE TABLE `counter` (`counter` INT( 20 ) NOT NULL,
`path` VARCHAR(255) IS NOT NULL);
在您的请求中,如果尚未存在,则创建一个新的空计数器。 如果它已经存在,你就增加它。
$mysqli = new mysqli("localhost", "root", "", "sitename");
// We get the counter the current URL
$counter = mysqli_query($mysqli, "SELECT counter
FROM counter
WHERE `path` = '" . $_SERVER['REQUEST_URI'] . "'";
if ($counter === NULL)
{
// If the counter does not exists yet, we create it
mysqli_query($mysqli, "INSERT INTO counter
VALUES (0, '" . $_SERVER['REQUEST_URI'] . "')";
}
// And we increment the counter
mysqli_query($mysqli, "UPDATE counter
SET counter = counter + 1
WHERE path = '" . $_SERVER['REQUEST_URI'] . "'");