Im doing a function to count visitors, views and page_views.
For now Im just trying to count page views but Im having a strange issue.
I have a table stats with this columns: "users,visits,page_views".
And now I just want to increment my page_views when user acess some page.
Every time I acess my homepage my page_views is incremented 1 unit, but when I acess a secundary page my column page_views is incremented with 3 units, and I want just also 1 unit.
Do you know why this can be happening?
I think that problem is in my getHome() function, because If I call my function countViews() before or after my getHome(), I have different behaviors. But Im not finding why.
When I have me countViews() above my getHome(), It seems that Im calling 3 times my function countViews on my secundary pages.
But I only call my function countViews() on my index.php file and below this function I have my getHome() function where I do my navigation to all pages I have in my project.
function countViews(){
$pdo = start();
//if Im not logged as admin
if(!isset($_SESSION['admin'])){
//So at first I read my table stats, if my table dont have any row,
// I create a row with my columns with value of '0'.
$readStats= $pdo->prepare("SELECT * FROM stats");
$readStats->execute();
if($readStats->rowCount()<1){
$insStats= $pdo->prepare("INSERT INTO stats(users, views, page_views) VALUES (?,?,?)");
$insStats->bindValue(1,'0');
$insStats->bindValue(2,'0');
$insStats->bindValue(3,'0');
$insStats->execute();
}
//If my table stats already have one row, I want to increment page_views.
else{
$resultStats= $readStats->fetch(PDO::FETCH_ASSOC);
$incrementPageViews = $resultStats['page_views'] + 1;
$updatePageViews = $pdo->prepare("UPDATE stats set page_views = ?");
$updatePageViews ->bindParam(1,$incrementPageViews);
$updatePageViews ->execute();
}
}
}
My index.php is like:
<?php
ob_start(); session_start();
require_once('dts/db.php');
$pdo = start();
countViews();
?>
<!DOCTYPE>
<!-- here I have my css and js imports -->
<?php getHome(); ?>
My secundary pages:
<title>Untitled Document</title>
</head>
<body>
<!-- here I have my html -->
</body>
getHome() function:
<?php
function getHome(){
$url = $_GET['url'];
$url = explode('/', $url);
$url[0] = ($url[0] == NULL ? 'index' : $url[0]);
if(file_exists('project/'.$url[0].'.php')){
require_once('project/'.$url[0].'.php');
}
elseif(file_exists('project/'.$url[0].'/'.$url[1].'.php')){
require_once('project/'.$url[0].'/'.$url[1].'.php');
}
else{
require_once('project/404.php');
}
}
?>
My table is like: