重复密钥更新上的Sql不起作用

时间:2014-09-08 13:05:39

标签: php mysql sql mysqli

我正在尝试在新计算机访问页面时插入新行(ip),但如果密钥(ip)已经存在,我只想更新访问计数器。

代码:mysqli_query($con,"INSERT INTO ip_address(ip, ip_count) VALUES (INET_ATON('$ip'),1) ON DUPLICATE KEY UPDATE ip_count = ip_count+1");

4次刷新后的

结果:

result

2 个答案:

答案 0 :(得分:-2)

   $ipaddr=<YOUR IP ADDRESS>;
   $sql="update ip_address set ip_count=ip_count+1 where ip_address='".$ipaddr."'";
   mysqli_query($con,$sql);

希望它能奏效。

答案 1 :(得分:-2)

您应该使用PHP来验证它是否已经存在

这只是一个例子,请使用注入安全方法,并为语法错误道歉,只是试图显示&#34;逻辑&#34;这里

$ip = '' // the way you save the IP address can be put here

$exists = "SELECT * FROM ip_address WHERE`ip` = '" . $ip . "'";
if(mysql_num_rows($exists) == 0) 
    {
      $insert = "INSERT INTO ip_address(ip, ip_count) VALUES (INET_ATON('".$ip."'),1)";
      $mysql_query($insert);
    } 
else 
    {
     while($result = mysql_fetch_assoc($exists))
      {
        $newCount = max($result['ip_count']) + 1;
        $update = "UPDATE ip_address SET ip_count = " . $newCount . " WHERE ip = '" . $ip . "'";
      }
}

基本上它通过提供的IP选择数据。如果它找不到,它会插入一条新记录。如果是,则获取max ip_count值并使用+1更新它。

同样,这很可能不会影响副本&amp;粘贴,您必须将其调整为您的脚本。

相关问题