PDA

View Full Version : PHP Hit Counter


mewrei
March 2nd, 2006, 05:51 pm
This is a simple yet powerful and scalable PHP hit counter that uses a MySQL database as its backend.

The first thing we need to do is connect to the database and select our DB


function db_connect()
{
$result = mysql_connect("server","username","password");
if(!$result)
{
echo 'Could not connect to database server';
exit;
}

$result = mysql_select_db("database");
if(!$result)
{
echo 'Could not access database';
exit;
}
}


This will connect to your database server then select the proper DB. This is assuming that you do have a DB set up for this purpose. You really only need a db with 1 table that has 1 column and 1 row.

The next set of instructions selects the table, grabs the current number of hits, then displays those hits, then increments the database count before returning the number to the database.


$sql = mysql_query("SELECT count FROM table");

if(!$sql)
{
echo 'Error, could not select count';
exit;
}

echo $sql.' people has viewed this page';

$sql++

$return = mysql_query("UPDATE table SET count =".$sql."");

}


And there's your program. I haven't tested this but it should work. Let me know if you want me to explain anything