Question

Below, I have pasted the code that I found the best way to do counter hits using PHP, MySQL and session. But I want to find out is there any other way to do this process? Or this way is only the way to do counter hits on session? I want to learn other ways as well, if you guys know it then it will be really helpful.

<?php
session_start();
include_once"db.inc.php";
$webpage=htmlspecialchars($_SERVER["REQUEST_URI"]);

$sql= "CREATE TABLE IF NOT EXISTS counter (
id int(4) NOT NULL auto_increment,
webpage varchar(90) NOT NULL,
visitors int(11) NOT NULL default '1',
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1"; 

mysql_query($sql);

$result=mysql_query("SELECT * FROM counter WHERE webpage='$webpage'");
$num_rows= mysql_num_rows($result);
if ($num_rows== 0){
mysql_query("INSERT INTO counter (id, webpage, visitors)
VALUES ('','$webpage','1')");

}else{

if (!isset($_SESSION['webpage'])){$_SESSION['webpage']= 0;
mysql_query("UPDATE counter SET visitors=visitors+'1' WHERE webpage='$webpage'");}}
?>

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Just a test </title>

</head>
<body> 

<?php
$result=mysql_query("SELECT * FROM counter WHERE webpage='$webpage'");
$row=mysql_fetch_assoc($result);
$n=$row['visitors'];
$l=9-strlen($n);
$z=substr('',0,$l);
$c="Counter: ".$z.$n;

echo "<div class='counter'>".$c."</div>";

mysql_close();
//session_unset();
//session_destroy();

?>
</body>
</html> 
Was it helpful?

Solution

I think there is no use of session while recording page hit :

if ($num_rows== 0){
mysql_query("INSERT INTO counter (id, webpage, visitors) VALUES ('','$webpage','1')");

}else{

// if (!isset($_SESSION['webpage'])){$_SESSION['webpage']= 0; /* you can remove this line */
mysql_query("UPDATE counter SET visitors=visitors+'1' WHERE webpage='$webpage'");}

And while viewing the count, remove some line, as those are useless...

$n=$row['visitors'];
//$l=9-strlen($n); /* you can remove this line */
//$z=substr('',0,$l); /* you can remove this line */
//$c="Counter: ".$z.$n; /* you can remove this line */
$c="Counter: ".$n;  /* removed $z  */

echo "<div class='counter'>".$c."</div>";

Hope this will help..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top