简体   繁体   中英

Error in php counter code

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

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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM