Php-mysql Course

This tutorial presents a Class that can be used to store and to count the number of accesses of files.
It can be used especially to counts the number of downloads.
This class, named CountAccess connects to a MySQL database with the PHP mysqli extension. It has three methods and Constructor:

- For more detailed explanations about the PHP instructions used in CountAccess class, see the comments inside class.

The CountAccess class

• Also, you can downlod this class (with a test file) from: CountAccess class
// - CountAccess class ( )
// stores and counts the number of accesses

class CountAccess {
 // define public properties for table name and its columns
 public $tb_name = 'access';
 public $tb_cols = array('urlf'=>'urlf', 'nrac'=>'nrac', 'dt'=>'dt');

 // protected property to store the connection to the MySQL server
 protected $conn;

 // Constructor
 public function __construct($server, $user, $pass, $db) {
 // create the connection to MySQL database (stores it in $conn property)
 $this->conn = new mysqli($server, $user, $pass, $db);
 if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit; }

 // check if table $tb_name exists in $db
 // if not exists, calls the setTable() method to create the table
 $Tables_in_db = 'Tables_in_'.$db;
 if($result=$this->conn->query("SHOW TABLES IN $db WHERE `$Tables_in_db` = '$this->tb_name'")) {
 if(mysqli_num_rows($result)<=0) {

 // method used to create the table
 private function setTable() {
 // sql query for CREATE TABLE
 $sql = "CREATE TABLE `$this->tb_name` (
 `". $this->tb_cols['urlf']. "` VARCHAR(88) PRIMARY KEY NOT NULL,
 `". $this->tb_cols['nrac']. "` INT(8) UNSIGNED DEFAULT 1,
 `". $this->tb_cols['dt']. "` TIMESTAMP
 ) CHARACTER SET utf8 COLLATE utf8_general_ci";

 // performs the $sql query on the server to create the table, on failure returns the error
 if (!$this->conn->query($sql) === TRUE) {
 echo 'Error create table: '. $this->conn->error;

 // method to insert / update the number of accesses of $urlf
 public function setAccess($urlf) {
 $urlf = $this->conn->real_escape_string($urlf); // escape special characters for use in the SQL query

 // sql query for INSERT / UPDATE
 $sql = "INSERT INTO `". $this->tb_name. "` (`". $this->tb_cols['urlf']. "`) VALUES ('$urlf') ON DUPLICATE KEY UPDATE `". $this->tb_cols['nrac']. "`=`". $this->tb_cols['nrac']. "`+1";

 // performs the $sql query on the server to insert / update the values
 if (!$this->conn->query($sql) === TRUE) {
 echo 'Error: '. $this->conn->error;

 // method to select the number of accesses (and the date-time of the last accessing) of $urlf
 public function getAccess($urlf) {
 $urlf = $this->conn->real_escape_string($urlf); // escape special characters for use in the SQL query

 // sql query for SELECT
 $sql = "SELECT `". $this->tb_cols['nrac']. "`, DATE_FORMAT(`". $this->tb_cols['dt']. "`, '%d-%m-%Y %H:%i') AS dt FROM `". $this->tb_name. "` WHERE `". $this->tb_cols['urlf']. "`='$urlf' LIMIT 1";

 // perform the query and store the results
 $result = $this->conn->query($sql);

 // if the $result contains at least one row
 if ($result->num_rows > 0) {
 // store the number of accesses and the date-time in a array
 while($row = $result->fetch_assoc()) {
 $re = 'Accesses: '. $row['nrac']. ', last: <i>'. $row['dt']. '</i>';
 else { $re = 'Accesses: 0, last: 0'; }

 // closes the statement, to free the memory

 return $re; // returns the string from $re

 /* Using the CountAccess class */

// sets data for connecting to mysql database (server_address, username, password and database_name)
$server = 'localhost';
$user = 'username';
$pass = 'password';
$db = 'db_name';

// create the MySQL connection and a instance of CountAccess class
$objCA = new CountAccess($server, $user, $pass, $db);

// if there is $_GET['urlf']
if (isset($_GET['urlf'])) {
 $urlf = trim(strip_tags($_GET['urlf'])); // delete tags and white spaces

 // calls the setAccess() method to insert / update the number of accesses

 // Redirects the browser to the URL stored in $urlf
 header("Location: " . $urlf); exit;

How to use the CountAccess class

1. Copy the code above in a PHP file (for example "class.CountAccess.php") on your server.
2. In this code, change the values of the $server, $user, $pass and $db variables, with your data for connecting to MySQL database. These variables are located after the line with "/* Using the CountAccess class */".
3. Build the download links whose number of accesses you want to count with the following form:
<a href="path/class.CountAccess.php?urlf=dir/" title="Download title">Download</a>
    - "path/class.CountAccess.php" - is the path to the PHP file with the CountAccess class.
    - "dir/" - is the path and the name of the file for download.

4. In the PHP page where you want to show the number of accesses, include this class (with include('class.CountAccess.php'); ).
Then, call the echo $objCA->getAccess($urlf);, where $urlf is the path and name of the file for download, the same with the address (or name) added in the "href" attribute, after the "urlf=".
                For example:     echo $objCA->getAccess('dir/');

The next example shows a PHP page which use the CountAccess class for two download links:
// include the file with CountAccess class
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "" >
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Count Downloads</title>

<!-- The Download links, via the class.CountAccess.php file -->
<a href="class.CountAccess.php?urlf=download/" title="Download test">Download Test</a> - 
<?php echo $objCA->getAccess('download/'); ?>
<br />
<a href="class.CountAccess.php?" title="Download Smile">Download Smile</a> - 
<?php echo $objCA->getAccess(''); ?>

This code will dislay something like:


Download Test - Accesses: 2, last: 21-04-2011 15:13
Download Smile - Accesses: 3, last: 21-04-2011 15:21
- The string which shows the number of accesses (downloads) can be modified from the getAccess() method, in CountAccess class.
- The date-time format can be changed in the getAccess() method, to the instruction "... DATE_FORMAT(`". $this->tb_cols['dt']. "`, '%d-%m-%Y %H:%i') ...", change the ('%d-%m-%Y %H:%i'), if you know how to.

• This class can be used to store, to count and display the number of accesses of any element (by a name, a URL, etc.).
    - Include the class in the PHP file in which you want to use it.
    - To insert / update the number of accesses, calls the method:   $objCA->setAccess('name');
    - To display the number of accesses and the date-time of last accessing, call:   echo $objCA->getAccess('name');
// include the file with CountAccess class

$name = 'a_string_value';
$objCA->setAccess($name); // insert / update the number of accesses for $name
echo $objCA->getAccess($name); // output the number of accesses and date-time

Daily Test with Code Example

Which tag can be used to create input text field in web page?
<form> <input> <div>
<input type="text" name="a_name" value="val" />
Which CSS property displays the text in a small-caps font?
display font-variant font-style
h3 {
  font-variant: small-caps;
What instruction displays a notice box with a message inside it, in JavaScript?
for() Date() alert()
var msg = "Visit";
Indicate the PHP code used to get the users IP.
echo $ip;
Count the number of downloads and accesses

Last accessed pages

  1. The School for Gods (4914)
  2. Validate radio and checkbox buttons (9511)
  3. PHP Unzipper - Extract Zip, Rar Archives (26846)
  4. querySelector and querySelectorAll (28676)
  5. Using server-sent events - EventSource (1310)

Popular pages this month

  1. PHP Unzipper - Extract Zip, Rar Archives (805)
  2. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (565)
  3. SHA1 Encrypt data in JavaScript (430)
  4. Create simple Website with PHP (397)
  5. Read Excel file data in PHP - PhpExcelReader (389)