Reputation:
I need to count the visitors in my website.
I don't know what mistake I done really. The counter is not adding periodically. How can I do this ?
Here is my Code :
<title>Page Counter</title>
<?php
include ('config.php');
$tbl_name="counter";
mysql_connect("$host", "$username", "$password")or die("cannot connect to server ");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$counter=$rows['counter'];
if(empty($counter)){
$counter=1;
$sql1="INSERT INTO $tbl_name(counter) VALUES('$counter')";
$result1=mysql_query($sql1);
}
echo "You 're visitors No. ";
echo $counter;
$addcounter=$counter;
$sql2="update $tbl_name set counter='$addcounter'";
$result2=mysql_query($sql2);
mysql_close();
?>
Upvotes: 0
Views: 60
Reputation: 596
Try this one
<title>Page Counter</title>
<?php
include ('config.php');
$tbl_name="counter";
mysql_connect("$host", "$username", "$password")or die("cannot connect to server ");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
if(empty($result))
{
$counter=1;
$sql1="INSERT INTO $tbl_name(counter) VALUES('$counter')";
$result1=mysql_query($sql1);
}
else
{
$rows=mysql_fetch_array($result);
$counter=$rows['counter'];
$counter=$counter + 1;
$sql2="update $tbl_name set counter='$counter'";
$result2=mysql_query($sql2);
}
echo "You 're visitors No. $counter ";
mysql_close();
?>
Upvotes: 0
Reputation: 1558
Please don't use mysql_*
functions. They are deprecated.
Learn instead mysqli
or PDO
.
You should correct your code to make it work
$addcounter = $counter + 1;
It would obviously set your counter direct to 2 by first call. So change also
if (empty($counter)) {
$sql1 = "INSERT INTO $tbl_name(counter) VALUES(0)";
$result1 = mysql_query($sql1);
}
Upvotes: 1