PHP PHP+Mysql实现网站顶和踩投票功能实例

alber1986 · 2020-02-15 17:22:30 · 热度: 13

PHP+Mysql实现网站顶和踩投票功能实例,通过记录用户IP,判断用户的投票行为是否有效,该实例也可以扩展到投票系统中。

首先我们在页面上放置“顶”和“踩”的按钮,即#dig_up和#dig_down,按钮上分别记录了投票的票数以及所占的百分比。

<div class="digg">  
    <div id="dig_up" class="digup"> 
        <span id="num_up"></span> 
        <p>很好,很强大!</p> 
        <div id="bar_up" class="bar"><span></span><i></i></div> 
    </div> 
       <div id="dig_down" class="digdown"> 
        <span id="num_down"></span> 
        <p>太差劲了!</p> 
        <div id="bar_down" class="bar"><span></span><i></i></div> 
    </div> 
    <div id="msg"></div> 
</div>

$(function(){ 
    //当鼠标悬浮和离开两个按钮时,切换按钮背景样式 
    $("#dig_up").hover(function(){ 
        $(this).addClass("digup_on"); 
    },function(){ 
        $(this).removeClass("digup_on"); 
    }); 
    $("#dig_down").hover(function(){ 
        $(this).addClass("digdown_on"); 
    },function(){ 
        $(this).removeClass("digdown_on"); 
    }); 

    //初始化数据 
    getdata("ajax.php",1); 

    //单击“顶”时 
    $("#dig_up").click(function(){ 
        getdata("ajax.php?action=like",1); 
    }); 
    //单击“踩”时 
    $("#dig_down").click(function(){ 
        getdata("ajax.php?action=unlike",1); 
    }); 
});

函数getdata()

function getdata(url,sid){ 
    $.getJSON(url,{id:sid},function(data){ 
        if(data.success==1){//投票成功 
            $("#num_up").html(data.like); 
            //通过控制宽度来显示百分比进度条效果 
            $("#bar_up span").css("width",data.like_percent); 
            $("#bar_up i").html(data.like_percent); 
            $("#num_down").html(data.unlike); 
            $("#bar_down span").css("width",data.unlike_percent); 
            $("#bar_down i").html(data.unlike_percent); 
        }else{//投票失败 
            $("#msg").html(data.msg).show().css({'opacity':1,'top':'40px'}) 
            .animate({top:'-50px',opacity:0}, "slow"); 
        } 
    }); 
}

ajax.php

$action = $_GET['action']; 
$id = 1; 
$ip = get_client_ip();//获取当前ip 

if ($action == 'like') { 
    likes(1, $id, $ip); 
} elseif ($action == 'unlike') { 
    likes(0, $id, $ip); 
} else { 
    echo jsons($id); 
}

投票的表结构

CREATE TABLE IF NOT EXISTS `votes` ( 
  `id` int(10) NOT NULL AUTO_INCREMENT, 
  `likes` int(10) NOT NULL DEFAULT '0', 
  `unlikes` int(10) NOT NULL DEFAULT '0', 
  PRIMARY KEY (`id`) 
) ENGINE=MyISAM  DEFAULT CHARSET=utf8; 


INSERT INTO `votes` (`id`, `likes`, `unlikes`) VALUES 
(1, 30, 10); 

CREATE TABLE IF NOT EXISTS `votes_ip` ( 
  `id` int(11) NOT NULL AUTO_INCREMENT, 
  `vid` int(11) NOT NULL, 
  `ip` varchar(20) NOT NULL, 
  PRIMARY KEY (`id`) 
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

本文转自:https://www.sucaihuo.com/php/105.html 转载请注明出处!

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册