php计数器代码出错

时间:2014-03-26 09:32:48

标签: php

我需要统计我网站上的访问者。

我不知道我做错了什么。计数器不会定期添加。我怎么能这样做?

这是我的代码:

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

2 个答案:

答案 0 :(得分:1)

请勿使用mysql_*个功能。它们已被弃用。

转而学习mysqliPDO

您应该更正代码以使其正常工作

$addcounter = $counter + 1;

第一次通话显然会将你的计数器直接设置为2。所以也要改变

if (empty($counter)) {
    $sql1 = "INSERT INTO $tbl_name(counter) VALUES(0)";
    $result1 = mysql_query($sql1);
}

答案 1 :(得分:0)

试试这个

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