note 45618 added to ref.mysql
| From: | (at) | Date: | Mon, 13 Sep 2004 07:02:52 +0000 |
| Subject: | note 45618 added to ref.mysql | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-76577@lists.php.net to get a copy of this message | ||
To count page hits, just put next code in a text file and include it in every one of your pages. It
will log even different querystrings as different pages. (a MySQL database and table is needed
first)
This can be a pretty good example of what you can do with PHP and MySQL. I made this script to log
and show all hits in: http://www.venezolano.web.ve/
<?php
/************************
This needs a MySQL table you can create with this:
CREATE TABLE
stats_pagecounter (
id int(25) NOT NULL auto_increment,
page_name varchar(255) NOT NULL default '',
page_hits int(25) NOT NULL default '0',
PRIMARY KEY (id)
) TYPE=MyISAM;
**************************
COUNTING STARTS
*************************/
function page_count($page) {
$c_link = mysql_connect('localhost', 'username', 'password')
or die('counter CONNECT error: '.mysql_errno().', '.mysql_error());
mysql_select_db('database_name');
$c_query = "SELECT * FROM stats_pagecounter
WHERE (page_name = '$page')";
$c_result = mysql_query($c_query, $c_link)
or die('counter SELECT error: '.mysql_errno().', '.mysql_error());
if (mysql_num_rows($c_result)) {
$row=mysql_fetch_array($c_result,MYSQL_ASSOC);
$pcounter = $row['page_hits']+1;
$c_update = "UPDATE stats_pagecounter
SET page_hits = '$pcounter' WHERE page_name = '$page'";
$c_hit = mysql_query($c_update, $c_link)
or die('counter UPDATE error: '.mysql_errno().', '.mysql_error());
} else {
$c_insert = "INSERT INTO stats_pagecounter
VALUES ( '0', '$page', '1')";
$c_page = mysql_query($c_insert, $c_link)
or die('counter INSERT error: '.mysql_errno().', '.mysql_error());
$pcounter = 1;
}
mysql_free_result($c_result);
mysql_close($c_link);
return $pcounter;
}
$phpself_url = $_SERVER['SERVER_NAME'].
$_SERVER['PHP_SELF'].'?'.
$_SERVER['QUERY_STRING'];
$page_hits = page_count($phpself_url);
/************************
COUNTING ENDS
*************************/
/************************
Put next line in a page to show his page hits
(If you want to)
************************/
echo $page_hits;
?>
----
Manual Page -- http://www.php.net/manual/en/ref.mysql.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+45618
Delete -- http://master.php.net/manage/user-notes.php?action=delete+45618&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+45618&report=yes
Search -- http://master.php.net/manage/user-notes.php