Free Online Articles Directory
18.11.2008 Sign In Register Hello Guest
Email:
Password:
Remember Me 
forgot your password?


Self-taught Php/mysql: a Simple Page Counter Tutorial

Author: Bill Hamilton Author Ranking Blue | Posted: 04-03-2008 | Comments: 0 | Views: 91 | Rating:  (71) Article Popularity - Blue (?) Got a Question? Ask.
Sign Up Now!

Self-Taught PHP/MYSQL: a simple Page Counter

This article is a short introduction to PHP and MySQL using the example of a simple page counter. I will illustrate creating the database in MySQL, connecting to the database from the PHP script, querying the database for information, displaying the information in a web page, and writing the information back to the database. As always, the fastest way to master the process is to jump right in with the code, look it over and use it. We’ll make a MySQL database to store the page names and the number of page views, and use PHP to increment and display the count on a web page. First here is all of the code, and then I’ll go over it in detail:

This goes into a file called “pagecounter.php”



You’ll no doubt have noticed that the script “includes” another, so without further delay here is the “connect.php” file:



The pagecounter.php script needs a database to operate on. Just briefly, here’s how to create it.

Creating the database:

Log in to MySQL at your Unix prompt (which might be #):

# mysql –uYourUserName –pYourPassword

At the MySQL prompt enter these commands:

mysql> create database pages;

mysql> use pages;

mysql> create table counter (pagename varchar(60),hits int, stamp timestamp);

mysql> quit;

Naturally you can create the database and table with utilities or web-based interfaces, but doesn’t it seem simpler to just enter three commands?

If you just wanted some code for a simple counter, this is all you need. Put this text into an SHTML web page, or this text into a php web page, copy the above two files into the same directory, and you’re done.

The first thing you’ll have noticed about the scripts are the dollar signs ($). All variables in PHP scripts start with a $. Anything starting with a $ is a variable. Instructions - statements and functions – end with a semicolon (;). starts the script and it ends with . When your script is hosed, look at these first.

Details about the pagecounter.php script

Line 1

include_once "connect.php”;

The first line in the script is just what it appears to be. It includes whatever is in the file “connect.php”. The “_once” means that it’s only included once, even if you had the line twice in the script. The reason I’ve separated it out is that it’s all the connection stuff to the database. All the php/Mysql scripts will need it, it’s always the same, so you can just put it by itself and use the include function.

Line 2

$pagename=$_SERVER["REQUEST_URI"];

The next line creates a variable called $pagename and sets the value to a special pre-defined variable $_SERVER["REQUEST_URI"]. The brackets [ ] are used by arrays in php. $_SERVER is a pre-defined array of headers and paths. This particular one is the name of the file that accesses the script, i.e., the name of the page that the counter is in.

Line 3

$result=mysql_query("Select * from counter where pagename='$pagename'");

All the database work is done with mysql_query, which sends an SQL command string to MySQL, after you’ve already logged in and connected to the database with the connect.php script. "Select * from counter where pagename='$pagename'" replaces $pagename with its value. But there’s a quirk here – the single quotes have to be inside the double quotes. If I had it the other way around, with the single quotes outside, the query would be for the text “$pagename” instead of the value. $result is the result set. It can be any name but in tutorial scripts it’s always $result, so it is here.

Line 4

if (mysql_num_rows($result)==0){

The fourth line is the php version of “if-then”. It simply checks whether there are any results from the query in line 3. The syntax is representative of php coding in general so it’s a good place to start. The curly brackets { } are used to group instructions. The curved brackets ( ) are used for the “if” condition. Everything inside the curly brackets will be executed if the “if” condition is true. PHP uses double equals == for comparison; if I had used only a single equal sign it would try to set mysql_num_rows to 0, which wouldn’t work for our purposes. A missing equal sign is the second thing to look for when your script is hosed and it’s not missing a $ or ;.

Line 5

mysql_query("insert into counter (pagename,hits) values ('$pagename','0')"); }

Inside the brackets, which only happens when line 4 finds no records of the page we searched for, the instruction creates a new record with the page’s name and zero for the hit count. Although mysql_query is a function, it doesn’t necessarily need a variable $result= in front of it. That’s optional in PHP if you don’t care about the return value.

The closing curly bracket } from the “if” statement comes here, since we only needed one statement to create our record.

Line 6

$count=mysql_result($result, 0, "hits");

mysql_result fetches the actual data from the result set. You specify the result set (from mysql_query), the row number (0), and the column name (“hits”). This is a little confusing at first since to get here took four steps: 1) log into MySQL, 2) connect to the database, 3) select data from the table, and 4) fetch a particular piece of the data. Putting the repetitive first two steps into an include file where you can more or less forget about them makes it more intuitive: use SQL to select data with mysql_query, and then retrieve data with mysql_result.

Line 7

$count=$count + 1;

Just adds one to the count variable. This is the count of the page views of the page requesting the script.

Line 8

mysql_query ("update counter set hits=$count where pagename='$pagename'");

As with Line 5 we send an SQL command directly to MySQL. This one updates the count for just the page matching the variable $pagename.

Line 9

echo "Page Count: ".$count;

The echo function writes text to a web page, in this case the text “Page Count: “ followed by whatever value is in $count. The period in between is the PHP concatenation operator: it simply adds the two strings together. Echo sees it as one string and outputs it.

Details about the connect.php script:

All this script does is connect to the MySQL server and select the Database.

Line 1

$host="localhost";$user="YourUserName";$password="YourPassword";$dbase="pages";

These are the inputs for the connect and select_db functions. Naturally you can insert the values into the functions on line 3 and 4 and eliminate this line, but it’s simpler to change later (when you re-use this code for example) if you just list them out at the top. The host and dbase won’t need to be changed in this example. The user and password are specific to your MySQL setup. As shown here you can put as many statements on one line as you want; PHP doesn’t care.

Line 2

// change the user and password to your MySQL user and password

The double slashes // denote a comment line that is ignored by php. Each comment line needs the slashes.

Line 3

$connect = mysql_connect($host,$user,$password);

You log into your MySQL with the mysql_connect command. You would change the host from “localhost” to the database server if you were accessing MySQL from another server, provided you’ve set up the access rights for the specified user/

Line 4

mysql_select_db($dbase,$connect);

Since we can have multiple databases in the MySQL server, we have to select one before sending SQL statements to it. As I mentioned earlier, this part is repetitive, and once it’s in this file and working you can forget about it.

In this tutorial we’ve examined a simple but functional web page counter implemented with PHP/MySQL. We examined the basic syntax of PHP statements and variables, the PHP “include” function and “if” control function, and the fundamental PHP MySQL functions mysql_connect, mysql_select_db, mysql_query, mysql_num_rows, and mysql_result. For further reference the reader should bookmark http://dev.mysql.com/doc/refman/6.0/en/index.html and http://us.php.net/manual/en/funcref.php .

Bill Hamilton is a former Database Administrator for United News and Media, and VNU inc. He currently operates several php/mysql driven websites including Gemstones and Beads

Rate this Article: Current: 5 / 5 stars - 1 vote(s).

Article Source: http://www.articlesbase.com/programming-articles/selftaught-phpmysql-a-simple-page-counter-tutorial-349813.html

Print this Article Print article   Email to a Friend Send to friend   Publish this Article on your Website Publish this Article   Send Author Feedback Author feedback  
Bill HamiltonAbout the Author:

Bill Hamilton is a former Database Administrator for United News and Media, and VNU inc. He currently operates several php/mysql driven websites including Gemstones and Beads

Submitting articles has become one of the most popular means to drive traffic to your website and promote yourself and your business. Join us today - It's Free!

Article Comments

Comment on this article Comment on this article
Your Name
Your Email:
Comment Body
Enter Validation Code: Captcha


Related Articles

Wonderful Source of Informational Technologies, Market and Web Tools
By: kolibrizas | 02/11/2007 | Programming
http://www.itwebmarket.com provides professional tutorials, web tools, free web templates to start your web business.

Reasons for choosing PHP / MySQL Web Hosting
By: Rodel Garcia | 21/09/2005 | Web Hosting
Feedback from your visitors or the data your MySQL database contains. You may need PHP features in your web hosting for the following reasons: [o] YOU NEED TO PROCESS.

People Still Cling To Their Unappreciated Cars
By: Daniel Millions | 09/08/2008 | Cars
Some people become emotionally attached to their cars because of sentimental value.

Way's To Sky-Rocket Your Profits
By: Ed Dunham | 06/05/2006 | Business
Ten way's to increase your profits.

Effective and Reliable E-commerce Hosting Services. How to Create E-store That Will Sell?
By: Anna Berk | 19/09/2007 | Web Hosting
Nowadays the World Wide Web represents not only the place used to store information and objective search instrument, but also plays a role of additional sales organization instrument. More and more companies places their websites in the Internet aiming to increase brand loyalty and popularize the business, get more new clients and partners. Internet regenerates and becomes one of the popular distribution channel of goods. In the 21st century, the era of technology and fast-growing markets, web site becomes instrument of vital importance for small trading company as well as for large one.

Using Php to Populate a Drop Down List Box From a Mysql Database Table
By: John Dixon | 05/09/2008 | Web Design
Drop down list boxes provide a great way to enable visitors to your web site to select an item on a form. Normally, you hard code the items on the drop down list box - but what about if you want to get the items from a database table.

Ignite Your Sales Now
By: Ed Dunham | 08/05/2006 | Sales
Ten way's to increase your profits.

Dotnetnuke Development
By: Alex | 01/11/2007 | Programming
About DotNetNuke Development

Got a Question? Ask.

Ask the community a question about this article:

Frequently Asked Questions

How can you restrict images from public view?
By: myed | 01-10-2008
The website I've setup allows members to upload pictures. The pictures are stored in a directory. How can I keep them from being viewed by the public. Should I do this with PHP and an .htaccess file?

Can you connect to two mysql databases on one php ...
By: myed | 30-09-2008
Can you connect to two mysql databases on one php page?

Can WHERE equal anything in a MySQL query?
By: myed | 28-09-2008
I'm trying to create one function to do a lot of different sorting. Can I make the default value of a WHERE argument equal to anything? So that the default value for that argument will find everything? function get_inventory ($order = 'id', $location = 'WA', $recalls = 'anything', $sold = '0') { $query = "SELECT * FROM v_inventory "; $query .= "WHERE location = '{$location}' and "; $query .= "recalls = '{$recalls}' and "; $query .= "sold = '{$sold}' "; $query .= "ORDER BY {$order} ASC"; $result = mysql_query($query, $connection); }

Parsing HTML with PHP
By: Daniel | 25-09-2008
Hi, What's the simplest way of parsing an HTML file using PHP? Thanks!

How to wirte a search message?
By: harimca | 19-09-2008
how to wirte a search message?

Due to some reason i have selected safe mode ...
By: zuber | 14-09-2008
due to some reason i have selected safe mode during starting of my computer, now i want to change the mode ,means from safe mode to normal mode. what is the procedure. my pc operating software is window vista

Q&A Powered by:
Powered by Yedda 

Latest Programming Articles

Cool Desktop Wallpapers
By: Danny | 18/11/2008
Cool desktop wallpaper is accomplishments arrangement that displayed in the computer operating system. The wallpapers usually be acclimated in JPEG, BMP and GIF book formats. That wallpaper can be acclimated with Microsoft Windows, Linux and Macintosh Mac OS. Each adviser can be altered requirements, alike admitting wallpaper images advised for accepted monitors can be scaled up or bottomward to the fit size. Those are accessible on the internet for free. Some categories of wallpapers are a

Tips for Buying Software Online
By: Daniel Jowssey | 17/11/2008
Buying software online not only helps save the planet, it also has other benefits, including: * Ease and Simplicity. You can purchase software in your underwear at 4am if you really want to. Shopping online doesn’t have to be done within regular business hours, nor do you need to look your best to do it. It’s also easy to shop around for the best prices and takes less time than driving to the shops.

Mvc Design Pattern
By: TuVinhSoft .,JSC | 14/11/2008
Model-view-controller (MVC) is an architectural pattern used in software engineering. In complex computer applications that present a large amount of data to the user, a developer often wishes to separate data (model) and user interface (View) concerns, so that changes to the user interface will not affect data handling, and that the data can be reorganized without changing the user interface.

Advantages of Low Cost Contract Programmers in Freelance Programming
By: Joanna Gadel | 12/11/2008
It observed that web industry is getting tougher thus the necessity of freelance contract programmer is required for developing more effective website with flexible features. This article states the fruitful advantages of freelance programmers in contract programming.

A Guide to Cnc Kits
By: Martin Applebaum | 09/11/2008
CNC kits are a way in which to construct your CNC machine. This article will provide some information on these machines.

A Guide to Cnc Tube Bending Machines
By: Martin Applebaum | 08/11/2008
Are you familiar with a CNC tube bending machine? This article will shed some light on the main function and components of this machine.

Ways to Hire Dedicated Php Programmers
By: Jucick | 08/11/2008
It’s not at all easy to hire dedicated PHP programmers unless you know where and how to find them. Whether you need to fix, update or enhance your website you naturally want the job done quick and right.

Top 4 Reasons Why Addressing Web Accessibility is Important
By: Matt Cave | 05/11/2008
There are very high chances that web accessibility is more important to the performance of your web site than you realize. Article takes a look at the top 4 reasons why it would be important to address the issue of web accessibility.

More from Bill Hamilton

Self-taught Php: String Functions Quick Start
By: Bill Hamilton | 11/06/2008 | Programming
A quick start reference for programmers who want to jump into PHP coding without wading through manuals and tutorials. It is strictly a first look with an abbreviated reference to the must-know string functions. The article provides basic string functions, process control and operators.

Article Categories





Give Feedback

Sign up for our email newsletter

Receive updates, enter your email below