PHP-MySql Hit Counter by OO PHP Pattern

Hello Friends, How are you?
Today I am going to learn how to make a Web Page Hit Counter by using PHP and MySql with Object Oriented PHP Pattern. For this work, we make only 2 files of PHP and 1 MySql Database with only one table. Lets go to start…

First of all, I am making a MySql database table for this. The database name should be ‘oophplearn‘ and table name should be ‘hitcounter‘. The structure of the table is below-

id count
 int (11)- Auto Increment  int(11)

Ok, now we are going to write our code. First of all, I am opening the notepad++ and create a new php file called ‘functions.class.php‘ . The code of this page is-

 

<?php

class Hitcounter{

//declaring the variables
public $command;

public function __construct(){

@mysql_connect(‘localhost’,’root’,”) or die(mysql_error());
@mysql_select_db(‘oophplearn’) or die(mysql_error());
}

//function for showing
public function showData(){

$sql = “SELECT * FROM hitcounter”;
$this->command = @mysql_fetch_array(mysql_query($sql));
return $this->command[‘count’];
}//  public function showData()

//function for update
public function updateData($value){

$newValue = $value + 1;

$sql = “UPDATE hitcounter SET count = ‘$newValue’ WHERE id = ‘1’”;
$this->command = @mysql_query($sql);

}//public function updateData($value){
}//class Hitcounter{

?>

Now, I am creating another php file called index.php and the code of this page is in below-

<?php

//includeing the functions.class.php file
require_once(‘functions.class.php’);
$fun = new Hitcounter();

//showing the valuse from Databse
echo ‘You are the user of : ‘;
echo $fun->showData();

//collecting the current value from databse
$value = $fun->showData();

//calling function for update
$fun->updateData($value);

?>

 

ok, we have almost finish our work. Now, we are going to test our work. Save all the works and browse your web path. I hope you will see our result as like in below-

You are the user of : 1

Thanks for reading this post. Keep in touch.

Allah Hafz…

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s