Go Back   Internet Business Forums > Design & Development

Closed Thread
 
Thread Tools Display Modes
Old 19-11-2006, 11:39 PM   #1 (permalink)
Senior Member
 
Join Date: Nov 2006
Posts: 225
Default Need a (PHP) counter

Hi, i want to use php & mysql to make a counter that tells ppl how many people on online at that moment. like a visitor counter kinda thing. DO you know how to create one / when to get one from? as well i need help with bookmark this page now and send this page to a friend, anything?? thanks a lot!!
roy77
roy77 is offline  
Old 20-11-2006, 06:05 PM   #2 (permalink)
Senior Member
 
Ljiljan's Avatar
 
Join Date: Nov 2006
Location: Bosnia and Herzegovina
Posts: 136
Send a message via MSN to Ljiljan
Default Re: hey guys - need your help again!

Well, you can use Extremetracking or Google Analytics
These are my favorites, the first one is visible (public) and other one is private and they have very good performances and results!
Ljiljan is offline  
Old 20-11-2006, 08:45 PM   #3 (permalink)
co-admin
 
army's Avatar
 
Join Date: Oct 2006
Location: Belgium
Posts: 666
Default Re: hey guys - need your help again!

Creating a PHP Hit Counter with MySQL.

This tutorial is a fairly straightforward introduction to using MySQL with PHP. We're going to build you a hit counter for your site. We will expand on this script in future tutorials, but for now, we're going to keep things extremely simple, with a few variables, some if statements, perhaps a loop or two, and a few of PHP's MySQL functions.

If you've never used, or even heard of, MySQL before then you will need to check with your web hosting company to make sure that your account supports MySQL databases, and that you know the following pieces of information before we start.

- MySQL Hostname (usually "localhost").
- MySQL Account Username
- MySQL Account Password
- MySQL Database Name (you may have multiple databases, so, check with your host if you're not sure what you're doing).

Also check, with your hosting company, what means you have at your disposal to access your database already. If you have a CPanel based hosting account, you will probably have access to phpMyAdmin, or some other similar such utility. If your account does not come with phpMyAdmin, or an alternative, you can download it from the phpMyAdmin Website. How to use phpMyAdmin and other tools for accessing your database are beyond the scope of this tutorial, and is something you should do some reading up on at the phpMyAdmin and MySQL websites if you're not too sure of what you're doing. This is not a MySQL tutorial, this is simply a PHP tutorial explaining how to connect to a MySQL database, read/write data, and display that data.

Anyway, assuming you have phpMyAdmin setup, or another alternative for accessing your MySQL database, you need to enter the following in order to create the table we're going to use.

PHP Code:
CREATE TABLE `hit_counter` (
  `
page_idINT11 NOT NULL AUTO_INCREMENT ,
  `
page_nameVARCHAR20 NOT NULL ,
  `
page_hitsINT11 NOT NULL ,
  
PRIMARY KEY ( `page_id` ) 
); 
This is our basic database table where the data will be stored. We have fields in which data will be stored.

- page_id : As each new URL is discovered by the hit counter, MySQL will automatically assign it a page_id. This value is used in various parts of the program to help distinguish between one database record and another
- page_name : This is the filename of the page being loaded.
- page_hits : This is the number of times the particular page has been loaded.

As I have said, this is a very basic introduction, and we aren't going to get into things like sessions and reload detection (when a user keeps reloading the same page over and over to bump up the hits), but this should get you started.

So, let's create a file called hitcount.php, and insert the below code into it.

PHP Code:
<?php

$dbase
['host'] = 'localhost';
$dbase['user'] = 'your_username';
$dbase['pass'] = 'your_password';
$dbase['name'] = 'database_name';

$dblink mysql_connect($dbase['host'], $dbase['user'],$dbase['pass']);
mysql_select_db($dbase['name'], $dblink);
Obviously, you will have to change "localhost", "your_username", "your_password" and "database_name" for the details specific to your database setup. But, what have we done here? Well, what we've done with these lines of code is to connect to MySQL, login and select the appropriate database containing your hit_counter table.

We learned from our basic PHP introduction that chunks of PHP code are opened with <?php and closed with ?> (a tag we've neglected to include at this point), and we've also learned that all lines in PHP end with the ; character. So, let's have a look at the remainder of the code.

You'll see the first 4 lines of code all contain what looks like a variable, but what's with all the ['host'], etc? Well, this particular type of variable is called an array. A variable is a container, and an array is a variable, however an array is a container of containers.

The actual variable name is "dbase", signified as a variable by the $ symbol at the beginning of the word. Whenever you see a variable with ['something'] after its name means that we're setting or reading a value inside an array of variables. This particular array variable contains four values. "host" is the hostname of your MySQL server, "user" is the username you use to login, "pass" is, of course, your password, and "name" is the name of the database you're going to be accessing. You can read more about arrays at the PHP Website.

Now, let's have a look at the two functions we've called, mysql_connect() and mysql_select_db(). mysql_connect(), as the name implies, connects you to the MySQL server and logs you in. It accepts up to 5 parameters, however we're only interested in the first three, which are the hostname to which we wish to connect, the username we want to login with, and the password belonging to that username. These are signified by $dbase['host'], $dbase['user'] and $dbase['pass'].

The mysql_select_db() function accepts up to 2 parameters, and here we're going to use both of them. The first parameter is the name of the database we wish to connect to, and the second is an identifier for MySQL queries, so we know which MySQL connection we want to use to select this database. The database name is defined by the $dbase['name'] variable. The second parameter is described below.

Now, you'll notice in I neglected to mention it when we spoke about the mysql_connect() line, but there's another variable, $dblink. This variable is called a resource identifier, which is kind of like giving a name to your connection.

In this example using a resource identifier is not so essential, but if your script connects to multiple databases, or even the same database with multiple different username & password combinations, resource identifiers are essential so that when you query the database, your script knows which MySQL connection to use.

The more advanced amongst you will notice that we've added no error checking in this script. Error checking is something that we'll go into in a future tutorial, or if you wish to see more information, and example source, regarding MySQL's error checking when attempting to connect and select a database, please see Example 1 at the mysql_select_db() page at PHP.net.

So, assuming our login details were correctly defined in the array variable, if we upload hitcount.php to our web server and load it in a browser, we should be confronted with a nice empty page. If this is what you see, then all is well. If you saw anything other than a blank page, then you're probably seeing error messages, so check you haven't made any typos, and that your login information is accurate.

Now that we're logged in, what can we do? Well, the first thing we want to do is determine the URL of the page we've just loaded. This is simply done by using the $_SERVER global variable that PHP so considerately provides for us.

PHP Code:
$page $_SERVER['REQUEST_URI']; 
As you can see, we've still not closed the PHP code segment yet, but don't worry, we will. $_SERVER holds a great many bits of information regarding the current transaction between the server and the browser, as well as some general server information. You can find out the IP address of the person currently running the script (loading the page), what web browser they're using (and thus the platform & operating system), whether user authentication has been used (via .htaccess or PHP authentication), the port being used to transfer the data, and a whole bunch of other things. You can read more about $_SERVER and other global variables here.

So, now we have the page name, so let's do something with it. The first thing we need to do is find out if the path already exists in the database. This is done with a simple MySQL query. Add these lines to the end of your hitcount.php file.

PHP Code:
$sql 'SELECT * FROM hit_counter where page_name = \''.$page.'\' limit 1';
$result mysql_query($sql$dblink);
$data mysql_fetch_assoc($result); 
As you may have spotted, each line starts with a variable name. The statement itself is stored inside the $sql variable. The contents of that variable are called with the mysql_query() function, and the result of the query is stored in $result. Now we use the mysql_fetch_assoc() function and have it pull the data from $result, and store it in the variable named $data - assuming, of course, that the path already exists in the database. If the MySQL query comes up empty and does not return a result, $data will be empty. $data, by the way, is an array variable. It stores three fields, the three fields of our database table that we created at the beginning of this tutorial. You can add these lines to your hitcount.php file to remind you what they are if you wish.

PHP Code:
// $data['page_id'] - This part of the array stores the ID of the record in the database for this page
// $data['page_name'] - This is the actual path & filename of the URL to which this record belongs
// $data['page_hits'] - This, surprisingly, is the number of hits the page above has received 
So, now we need to check that $data actually contains some data. If it does, we need to increment the counter by 1, then write it back to the database, overwriting the previous record. If $data does not contain any data, we know this is the first time this particular page has been loaded, and so we have to create a new record in the database and give it a single hit. So, here's a few more lines for you to put at the end of your hitcount.php file.

PHP Code:
  $data['page_hits']++;
  
$sql 'UPDATE hit_counter SET page_hits = \''.$data['page_hits'].'\' where page_id = \''.$data['page_id'].'\'';
  
$result mysql_query($sql$dblink); 
} else {
  
$sql 'INSERT INTO hit_counter (page_id, page_name, page_hits) VALUES (\'\', \''.$page.'\', \'1\')';
  
$result mysql_query($sql$dblink); 
}

?> 
As you can see, we do this with relatively few lines of code. But, let's break it down.

First the if statement. "If" checks the value of something, and if that value returns true, performs a specified action. If the condition is not true, you can have it check something else, or several something elses, or simply perform a different set of actions.

In this case, we're saying "if ($data)". Which, in plain English, basically means "if $data exists do something". As I said earlier, if the current URL previously exists in the database, $data will have something contained within it, so it will exist, and return true. If a result was not pulled from the database, and this page is being loaded for the first time, $data will not exist, and the condition will return false, and the first set of actions will not be performed.

So, what's done if something is stored inside $data? Well, the first thing we do is increment the number of hits the page has had. If you have an integer (a whole number) stored inside a variable, you can add ++ to the end of it to have it increment by 1, which is what we've done here. The next thing we do is to create another MySQL query that will update the existing record in the database. As we've already got something stored inside $data, it's generally more reliable to use $data['page_id'] as a comparison rather than the path of the page. So, we update the record with the new hit count. Then we execute this query using the $sql variable contents.

And if the page was not already in the database and $data does not exist? Well, here we insert a new record into the database, and give it 1 hit. We don't use a value for page_id, as this is automatically generated by MySQL when we create a new record due to the auto_increment flag set on this field. Again, we store the query inside the $sql variable, then run that query using the mysql_query() function.

And finally you'll notice that we close our script with the ?> tag.

So, before I carry on, here's all the code in a single chunk.

PHP Code:
<?php

$dbase
['host'] = 'localhost';
$dbase['user'] = 'your_username';
$dbase['pass'] = 'your_password';
$dbase['name'] = 'database_name';

$dblink mysql_connect($dbase['host'], $dbase['user'],$dbase['pass']);
mysql_select_db($dbase['name'], $dblink);
$page $_SERVER['REQUEST_URI'];
$sql 'SELECT * FROM hit_counter where page_name = \''.$page.'\' limit 1';
$result mysql_query($sql$dblink);
$data mysql_fetch_assoc($result);
// $data['page_id'] - This part of the array stores the ID of the record in the database for this page
// $data['page_name'] - This is the actual path & filename of the URL to which this record belongs
// $data['page_hits'] - This, surprisingly, is the number of hits the page above has received 
if ($data) {
  
$data['page_hits']++;
  
$sql 'UPDATE hit_counter SET page_hits = \''.$data['page_hits'].'\' where page_id = \''.$data['page_id'].'\'';
  
$result mysql_query($sql$dblink); 
} else {
  
$sql 'INSERT INTO hit_counter (page_id, page_name, page_hits) VALUES (\'\', \''.$page.'\', \'1\')';
  
$result mysql_query($sql$dblink); 
}

?>
your pages. If you have a single header.php file that you call on each page you can put the line at the top of that file. If not, you will need to add the following line to each .php page that outputs content on your site.

PHP Code:
<?php include('hitcount.php'); ?>
This will cause the script to be run each time a page including the file is loaded.

By the way, as we haven't mentioned them before, those three lines starting with // are comments. There are two main ways to define a comment, either by using //, which comments everything from that point on to the end of the line, and using /* */ pairs. Using /* */ your comments can span multiple lines. Thus, those three lines above could've been written as :

PHP Code:
/*
  $data['page_id'] - This part of the array stores the ID of the record in the database for this page
  $data['page_name'] - This is the actual path & filename of the URL to which this record belongs
  $data['page_hits'] - This, surprisingly, is the number of hits the page above has received
*/ 
It's generally good practice to heavily comment your code throughout its development. It serves as an aid to memory when you go back several days, weeks or even months later to edit the code, as well as to allow others looking at your code to know what's going on.

Part 2 of this tutorial will detail various methods we can use to actually display the number of hits your pages have received. But, if you go ahead and set this up on your site now, you can start collecting some hits statistics for us to play with in the next tutorial.

Have fun!
army is offline  
Old 20-11-2006, 08:46 PM   #4 (permalink)
co-admin
 
army's Avatar
 
Join Date: Oct 2006
Location: Belgium
Posts: 666
Default Re: hey guys - need your help again!

Also look here: http://www.betlik.com/script-visitor-counter-t697.html
army is offline  
Old 21-11-2006, 01:56 AM   #5 (permalink)
Senior Member
 
Join Date: Nov 2006
Posts: 225
Default Re: hey guys - need your help again!

ARMY! You are the best army ever! i love you man, such knowlege and sharing, thanks!!!!! roy77
roy77 is offline  
Old 21-11-2006, 12:19 PM   #6 (permalink)
Senior Member
 
Ljiljan's Avatar
 
Join Date: Nov 2006
Location: Bosnia and Herzegovina
Posts: 136
Send a message via MSN to Ljiljan
Default Re: hey guys - need your help again!

Thank you for sharing these scripts army
Ljiljan is offline  
Old 21-11-2006, 08:30 PM   #7 (permalink)
co-admin
 
army's Avatar
 
Join Date: Oct 2006
Location: Belgium
Posts: 666
Default Re: hey guys - need your help again!

I am glad I could help you all out .
army is offline  
Old 22-11-2006, 08:04 PM   #8 (permalink)
Senior Member
 
moinuddin102's Avatar
 
Join Date: Oct 2006
Posts: 216
Default Re: hey guys - need your help again!

visit to http://www.www.hotscripts.com/PHP/Sc...ers/index.html
you can find there many visitor counter.
moinuddin102 is offline  
Old 23-11-2006, 04:41 PM   #9 (permalink)
Junior Member
 
Join Date: Nov 2006
Posts: 27
Default Re: hey guys - need your help again!

Thank you for sharing script.
I want thanks also Ljiljan for his link.
And Thanks to webmaster give me chance to collect so much informaion.
munmun is offline  
Old 23-11-2006, 09:50 PM   #10 (permalink)
co-admin
 
army's Avatar
 
Join Date: Oct 2006
Location: Belgium
Posts: 666
Default Re: hey guys - need your help again!

Quote:
Originally Posted by munmun View Post
Thank you for sharing script.
I want thanks also Ljiljan for his link.
And Thanks to webmaster give me chance to collect so much informaion.
If I am the "Webmaster", I only can say, I am glad I am able to help you . If not ... erm ... not them, right?
army is offline  
Closed Thread

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


All times are GMT +1. The time now is 07:48 AM.


Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.1.0 ©2007, Crawlability, Inc.