Posted in php
816
2:01 am, September 23, 2021

How to record your own page views with PHP, and make them into weekly monthly and yearly charts

Building a better Simple Page View Counter

Currently this site has a very basic view counter on it. 

Here is how it currently works.

Load the page, function checks if the page has a existing record for this class and page uid, if it does not have one then it adds one with the hit value of 1, if it already finds a record for it, then it loads that value and adds one to it. You can see this currently working as you reload the page, and the counter goes up. This is fine for a very basic hit counter, but we can add a lot more functionality to this with the addition of just a couple of extra fields. 

Lets add the following fields.

PHP

Week Number = $this->week = date("W"); // week as a number from 1-52
Month Number = $this->month = date('m'); // month number 01 - 12
Year Number = $this->year = date('y'); // year number

Im not sure if i want to drill all the way down to Day Number as this may create a few too many database records. As it is with the week month and years it will create for each page that has the hit counter enabled a record, so the more fields i add, the more it will add to the table, even though the table size is negligible. 

The only issue with this kind of data is that is keeps expanding, unless we add some kind of delete function to it after a certain amount of time, like only keeping the hits data for a year or that kind of thing. 

After a year or so, you could delete the weekly and monthly data and just archive it to a yearly view maybe, just need to keep an eye on the table sizes.

Add View Function

Here is how i would add the view on each page. 

PHP

// in the class add
public $fields_array = array();

// add a game view.
    $views->title = $class->title;
    $views->fields_array["linked_class"] = $p2;
    $views->fields_array["linked_uid"] = $p3;
    $views->add_view();
```

```php
public function add_view() {
        $this->week = date('W');
    $this->month = date('m');
    $this->year = date('y');
        $this->fields_array["week"] = $this->week;
    $this->fields_array["month"] = $this->month;
    $this->fields_array["year"] = $this->year;
    $fields_array = $this->fields_array;
    if($this->load_from_fields_array($this->fields_array, $max = 1)) {
      // update loaded
      // echo "update
";       $this->views = $this->views + 1;       $this->update();     } else {       // add new       //echo "add
";       $this->linked_class = $this->fields_array["linked_class"];       $this->linked_uid = $this->fields_array["linked_uid"];       $this->views = 1;       $this->add();     }     return;   } ```

Then with this new data we could add some graphs based on hits per week per post or per month, etc. 

then at the end of each page i could write a sentence saying, this page has had number views today, this week, month etc, or make a nice table with that data. 

Thoughts

I was just thinking about this and i think its going to add a new record per day month year, is that ok?

so for every day it will add a new row per page, which could add up to a lot of rows. 

how to extract daily hits data from this. 

need functions to extract details based on day and week

it will do views this week, month and year. so that should not be too much data.

i think i will do seperate functions to extract views numbered by week month and year totals. 

Extracting Views this week

this should extract the views for this week total for the specified linked class and uid. 

PHP

  public function views_week_single() {
    global $functions;
    $out = "";
    $db_table_name = $this->db->escapeString($this->db_table_name);
    $linked_class = $this->db->escapeString($this->fields_array["linked_class"]);
    $linked_uid = $this->db->escapeString($this->fields_array["linked_uid"]);
    $week_num = $this->db->escapeString($this->fields_array["week_num"]);
    $sql = "select * from $db_table_name where
      linked_class = '$linked_class' and
      linked_uid = '$linked_uid' and
      week_num = '$week_num'
      order by hits desc limit $start,$max";
    $result = $this->db->query($sql);
    $views_total = 0;
    while($row = $result->fetchArray()) {
      $views = $row['views'];
      $views_total = $views_total + $views;
    }
    return $views_total;
  }

Lets add that to a widet under the page content. Something like this

Still to do, Month and Year and then all hits totals. 

Views Widget Template

HTML

<style>
  .view-title {
      text-transform: uppercase;
      font-weight: bold;
      font-size: 12px;
      color: #62b174;
      margin-bottom: 5px;
      padding-bottom: 5px;
      border-bottom: 1px solid #3a3a3a;
  }
  .view-number {
      text-transform: uppercase;
      font-weight: bold;
      font-size: 32px;
      color: #FFF;
  }
</style>
<div class='card mb-3 view-stats'>
  <h5 class='card-header'>View Statistics</h5>
  <div class='card-body'>
    <div class='row'>
        <div class='col'>
          <div class='view-title'>
            This Week
          </div>
          <div class='view-number'>
            [@views_week_single]
          </div>
        </div>
    </div>
  </div>
</div>

Data seems to be recording ok, after leaving it for a night or so. 

View Statistics
This Week
84
This Month
636
This Year
816

No Items Found.

Add Comment
Type in a Nick Name here
 
Other Items in php
sqlite fetchArray into another array php return json header and content list_all_array an early stages of list all function that uses an array to pass in main variables replace singular variable assignment with an array loop and variable variables using the $_SERVER['HTTP_REFERER'] to check referring pages timeline class and function php html template class system views list function for checking what views have been made on the current week load array load all items from an array while in a sqlite load sql loop create a 200 character summary from a longer html string using strlen to check the length of a string and do something about it How to record your own page views with PHP, and make them into weekly monthly and yearly charts load from fields array php class function get the current week as a number with php creating embedded php code from a database field test php bundle write check if a file exists with php check if the file is a directory or check if the directory exists in php get the current working directory in php create directory with php create folder with php check if a product already exists by its md5 load random videos module using template PHP/SQLite - Load Random Item split a string into links using the comma extract youtube image from video url simple php ip blocker preg replace clean a string only allow a-zA-Z0-9 characters get last month as a number with php verify the google recapture server php rtrim strip white space or strings from the end of a string get the current month as a number show the difference between two dates in years, months, days, hours and seconds counting the occurrence of words in a multidimensional array write string contents to a file with php unable to access the $_FILES when submitting a form php check column exists in table sqlite show all methods or functions in a class (class function version) show all methods (functions) in a class adding an item to an array with php passing in arrays to your functions rather than using variables check server https or http value in php using $_SERVER Remove background image php with image magic get current url with php list a functions variables or arguments php list all the functions in a class php print an array nicely add a toast alert when logging in with half moon dont use md5 for password hashing using password_hash and password_verify php basic page router checking for spam comments function
Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

Join me on Substack if you want me to send you a collection of the things i have done or found or read for the week. Or follow me on twitter if you prefer, i dont post much but i probably should!

❤👩‍💻🕹

Random Quote
I'm a big believer in energy and the secret and that sort of thing.
Unknown