November 04, 2003

Creating a MultiPage Text Counter (PHP/DBX)

Tutorial on how one can write a very basic MultiPage Text Counter which uses DBX to store its data.

To have the counter running, we will require to have a database and a table. If you do not have the database created already or wish to make another database you do it by using the query below:

<?php
    include("/path/to/dbx");
    $DBase=new dbx;
    $DBase->dbx_query("create database dbname");


The following query will create the table needed by the multipage counter script:

$DBase->dbx_query("select database dbname");
    $DBase->dbx_query("create table counter(url varchar(255),count int)");
    ?>


Now we have created the required table. We now need to make the counter script that will update or insert pages and their count in the database. We will call this file counter.php

<?php
    include("/path/to/dbx");
    $DBase=new dbx;
    $DBase->dbx_query("select database $dbname");

    $url=$PHP_SELF;
    $q=$DBase->dbx_query("SELECT * FROM $dbtable WHERE url='$url'");

    // URL exists in database, so we will need to update the count in this case.
    if($result=$DBase->dbx_fetch_array($q)) {
    $cnt_val=$result[COUNT]++;
    $DBase->dbx_query("UPDATE $dbtable SET count='$result[COUNT]' WHERE url='$result[URL]'");
    }
    // URL doesn't exists in database, so we will need to insert a new row.
    else {
    $DBase->dbx_query("INSERT INTO $dbtable VALUES('$url','1')");
    $cnt_val=0;
    }

    echo "This page has been viewed ".$cnt_val+1." times";


    ?>


Now we are ready to show the counter on our pages. We can simply use the following code in any php file and the counter for that URL will show up.

<?php
    include("counter.php");
    ?>


Posted by Jayant Kumar Gandhi at November 4, 2003 03:33 PM | TrackBack
Comments
Post a comment









Remember personal info?