Thursday, November 21, 2013

Storing the Total Number of times a Page is viewed

A quick one on how to do a page view count on your site using php.
The code below can be manipulated to achieve other objective depending on your level of understanding on how the code works, it is straight to the point, all you need do is to create a database e.g named PageView  using PhpMyAdmin and run the SQL below to generate your table the create a new php page and insert the code PHP bellow that is all. run the the page and see what happened and also refresh PhpMyAdmin and see the inserted records including the page URL itself.
if this information do help you do remember to leave a comment or subscribe for more. 
SQL:

REATE TABLE IF NOT EXISTS `views` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `page` varchar(150) NOT NULL,
  `datetime` datetime NOT NULL,
  `newsid` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=28 ;

PHP
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_conn = "localhost";
$database_conn = "
PageView";
$username_conn = "root";
$password_conn = "root";
$conn = mysql_connect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
?>


<?php
if (isset($_SERVER["SCRIPT_NAME"])){
mysql_select_db($database_conn, $conn);
$query2 = "INSERT INTO views (page, datetime,newsid) VALUES ('".$_SERVER["SCRIPT_NAME"]."', CURDATE(), '$_SESSION[newsid]')";
$result2 = mysql_query($query2,$conn);

$query3="SELECT COUNT(*) as total FROM views WHERE newsid='$_GET[newsid]'";
$result3=mysql_query($query3,$conn);
while($data=mysql_fetch_array($result3)){
    $count = $data['total'];
}
}

 echo $count;
?>

No comments:

Post a Comment