| A Multi-Page Counter Script using PHP/MySQL |
|
|
|
| Webmaster Articles - Scripts & Scripting |
| Written by TDavid |
|
Back on http://www.php-scripts.com/php_diary/1/09/2001.php3, I showed people how to make a simple counter using a flat file data system and over time this has proven to be one of the more popular diary entries (by reader rating) that I've ever written. One thing you couldn't do with that particular script was to have more than one counter (unless you modified it considerably). So what if one wanted to have counters on multiple pages on the website using one script? Today let's create a script to do this using mySQL. The first thing we need to do is plan out our mySQL table structure. CREATE TABLE tds_counter Explanation of fields in the mySQL table: COUNT_ID - this controls the unique counter ID so we can have many different counters What if I don't have Telnet access?It's not the end of the world if you don't have telnet access on your server, you can still write a PHP script that will build the new table for you. Let's create such a script that creates the table and then inserts our first counter page (this one) into the table. <? mysql_query($create_query, $mysql_link); $insert = "INSERT into tds_counter VALUES ( mysql_query($insert, $mysql_link); ?> The counter code itselfThe counter code is really pretty easy. We look for a valid ID number coming in and then increment the counter if it is. I'm adding an additional variable called $inv which will be a flag to indicate whether the counter value should be shown or not. We want to make sure the input is a number, if not, we ignore the counter for security purposes. <? Since we inserted this page when we created the table this page would be COUNT_ID #1, or abbreviated $cid=1. To insert our counter in the php-enabled web page (php, phtml, php3 extension usually) we use the require function and a format like this: <? $cid=1; require("counter.php"); ?> ADVANCED USERS: Reusable function?You could easily wrap the code above in a reusable function as follows: <? To call this function from within another script you would use: pushCount($cid, 0); // visible counter If you decide you want to use more than one counter all you have to do is insert a new record into the table and reference that $cid. Now you can call as many different counters as you want on your website. You could put the same counter code on multiple pages and get an aggregate count of all pages as well. You can see examples of this code, (including viewing the complete source) by visiting: http://www.php-scripts.com/php_diary/021901.php3 and read other diary entries I have contributed over time to php-scripts.com. |



