如何检索有关用户的特定数据?

时间:2015-08-10 05:19:38

标签: php mysqli

我想创建一个系统,如果用户多次点击任意广告,广告就会被隐藏。当他们进入我的网站时,它会检查他们的IP是否在数据库中,如果没有,那么他们的IP将被存储。接下来,它会检查到目前为止他们有多少次点击,如果超过1个广告将被隐藏。这是我现在正在努力的部分。我已经在下面的代码中评论了我想要发生的事情。另外,我的表中有4列:id,ip,count(点击次数)和日期时间。我正在使用mysqli,我只想知道如何根据用户的IP检索用户的点击次数。以下是Stats表的示例:id:1 ip:xx.xx.xx.xx count:0 creation:datetime

if (!empty($_SERVER['HTTP_CLIENT_IP']))  
{
   $ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   
{
   $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
   $ip = $_SERVER['REMOTE_ADDR']; 
}
$query = "SELECT count(*) FROM Stats WHERE ip = '$ip'";
$result = $db->query($query); 
if($result->num_rows > 0)
{
    //if user's click count > 1
    hide ads
    else
    display ads         
}
else {
   $insert = $db->prepare("INSERT INTO Stats(ip, created) VALUES (?, NOW())"); 
   $insert->bind_param('s', $ip);
   $insert->execute();
   $insert->close();
}

2 个答案:

答案 0 :(得分:2)

您需要使用AS关键字为汇总创建别名,才能从fetch_assoc访问它。

$query = "SELECT count(*) AS total FROM Stats WHERE ip = '$ip'";    

if ($result = $db->query($query)) {

$data = $result->fetch_assoc();

    if($data['total']>1){
        // This user already clicked on at least one AD. Don't show ADS.     
    }else{
        // This user haven't clicked an AD yet. Show ADS.
    }
}

替换

if($result->num_rows > 0)

if($data['total']>1)

因为它不再需要了。谢谢@Shehary指出这一点。

答案 1 :(得分:0)

  mysql_query("SELECT * FROM Stats WHERE ip = '$ip'") or die(mysql_error());    

  if (mysql_affected_rows()){
    // This user already clicked on at least one AD. Don't show ADS.     
  }
  else {
   // This user haven't clicked an AD yet. Show ADS.
  }