Posted in php
14699
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
439
This Month
1965
This Year
4130

No Items Found.

Add Comment
Type in a Nick Name here
 
Other Items in php
php redirect echo the page id from wordpress sqlite escape string Deprecated: parse_str(): Calling parse_str() without the result argument is deprecated getcwd usage in php to get the current working directory for file includes write to file php save string to file php using preg_match to extract text from elements encode spaces in items passed to url to %20 not + php function load as table - load_as_table turn on or off error reporting php get json with php from a url and display it php convert number with k on the end to full number extract variables from url string php No 'Access-Control-Allow-Origin' header is present on the requested resource. Fatal error: Uncaught Exception: Required extension GD is not loaded. php check if a class exists Uncaught Error: Call to undefined function mb_convert_encoding() get the subdomain name from the domain string in php - sub domain fixing error Call to undefined function simplexml_load_string get the content of a url get the content of a link with php and test if the result is empty php check if url is valid with filter_var php save csv from array to file php export csv from string to browser download convert json string to a php array how to json encode an array in php how to decode xml in php php get file and save it php function to remove the query string from a url using php parse_url function to remove the query string from a url add every value in the load_array array into the out for testing Fix for PHP Warning Trying to get property '*name*' of non-object write the contents of a url into a file with 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
Related Search Terms
Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code here, mostly for my reference. Also if i find a good link, i usually add it here and then forget about it. more...

Subscribe to weekly updates about things i have added to the site or thought interesting during the last week.

You could also follow me on twitter or not... does anyone even use twitter anymore?

If you found something useful or like my work, you can buy me a coffee here. Mmm Coffee. ☕

❤️👩‍💻🎮

🪦 2000 - 16 Oct 2022 - Boots
Random Quote
Don't look to be the next Facebook, try to solve a real problem instead.
Unknown
Random CSS Property

resize

The resize CSS property sets whether an element is resizable, and if so, in which directions.
resize css reference