访客ips和计数器不更新

时间:2017-12-15 04:19:10

标签: php mysqli remote-access

我创建了一个网站,现在我想要访问者ips,所以我从php中的远程地址获取它,现在我想要做同一个用户访问我的网站更多只有计数器将增加而不是ips。所以我创建了一个带有id,ip,date和cntr column的表计数器。但是当我运行我的php页面时,我的页面不允许任何ip插入或删除所以帮助我。我的代码在下面,

<?php
$username="root";
$password="";   
$servername="localhost";
$database="ips";
$tableName="ips";

error_reporting(E_ALL);
ini_set('display_errors', '1');

$ip = ($_SERVER['REMOTE_ADDR']);
//echo $ip;
$con = mysqli_connect($servername,$username,$password,$database);
if (mysqli_connect_errno($con))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query2=mysqli_query($con,"select cntr,ip from counter")or die(mysqli_error($con));
while($row=mysqli_fetch_array($query2))
{
    echo $row['ip'];
    echo $row['cntr'];

    if($row['ip']== $ip)
    {
        mysqli_query($con,"update counter set cntr = cntr+1 where ip = '$ip'");
    }
    else
    {
        mysqli_query($con,"insert into counter (ip,date,cntr) values ('$ip',now(),1)");
    }
}
$_SESSION['status'] = true;
?>

2 个答案:

答案 0 :(得分:1)

你的循环在逻辑上是不正确的: 让我们假设您在计数器表中有100行具有唯一IP。在循环中,您插入99行并仅更新与现有IP($ ip)对应的一行,如果未找到相应的IP,则插入具有相同IP($ ip)的100行。

首先,我会检查表计数器中是否存在IP,如下所示:

$sql = "select count(*) as cnt from counter where ip = '$ip'";
// check if IP is already stored
$check = mysqli_fetch_array(mysqli_query($con, $sql));

然后继续插入或更新:

if($check['cnt'] > 0) { 
    // ip is present, update record (your query is fine)
} else {
    // ip not present, insert new record (your query is fine)
}

使用此方法无需检查表是否为空。 您还需要确保字段cntr未初始化为NULL,否则+1将不适用于您的更新查询。

答案 1 :(得分:0)

基本上你的代码可以工作。但是当您的数据库为空并且指出了逻辑问题时,您必须注意。您必须先插入至少一个数据行。

请尝试以下代码:

$username="root";
$password="7528282";   
$servername="localhost";
$database="stackoverflow";
$tableName="ips";
error_reporting(E_ALL);
ini_set('display_errors', '1');

$ip = ($_SERVER['REMOTE_ADDR']);
//echo $ip;

$con = mysqli_connect($servername,$username,$password,$database);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$query2=mysqli_query($con,"select cntr,ip from counter")or die(mysqli_error($con));
//add this to judge whether the database is empty
if(mysqli_num_rows($query2)){
    $found=false;
    while($row=mysqli_fetch_array($query2))
    {
        echo $row['ip'];
        echo $row['cntr'];

        if($row['ip']== $ip)
        {
            mysqli_query($con,"update counter set cntr = cntr+1 where ip = '$ip'");
            $found=true;
            break;
        }
    }
    if(!$found){
        mysqli_query($con,"insert into counter (ip,date,cntr) values ('$ip',now(),1)");
    }
}
//if the database is empty, insert one row first
else{
    mysqli_query($con,"insert into counter (ip,date,cntr) values ('$ip',now(),1)");
}
$_SESSION['status'] = true;