0

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();
?>
3
  • try $counter=mysql_num_rows($result); Commented Mar 26, 2014 at 9:35
  • You'll need to create a loop to iterate over the $rows rowset. Commented Mar 26, 2014 at 9:35
  • Avoid using mysql driver, they are not safe enough and will be dropped in further PHP version. Commented Mar 26, 2014 at 9:36

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@user3388086 So you can mark my answer as correct ;-)
0

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();
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.