搜尋
首頁後端開發php教程基于PHP+jQuery+MySql实现红蓝(顶踩)投票代码_PHP

先给大家展示效果图:

查看演示 下载源码

这是一个非常实用的投票实例,应用在双方观点对抗投票场景。用户可以选择支持代表自己观点的一方进行投票,本文以红蓝双方投票为例,通过前后台交互,直观展示红蓝双方投票数和所占比例,应用非常广泛。

本文是一篇综合知识应用类文章,需要您具备PHP、jQuery、MySQL以及html和css方面的基本知识。

HTML

我们需要在页面中展示红蓝双方的观点,以及对应的投票数和比例,以及用于投票交互的手型图片,本例以#red和#blue分别表示红蓝双方。.redhand和.bluehand用来做手型投票按钮,.redbar和.bluebar展示红蓝双方比例调,#red_num和#blue_num展示双方投票数。

<div class="vote"> 
 <div class="votetitle">您对Helloweba提供的文章的看法?</div> 
 <div class="votetxt">非常实用<span>完全看不懂</span></div> 
 <div class="red" id="red"> 
 <div class="redhand"></div> 
 <div class="redbar" id="red_bar"> 
  <span></span> 
  <p id="red_num"></p> 
 </div> 
 </div> 
 <div class="blue" id="blue"> 
 <div class="bluehand"></div> 
 <div class="bluebar" id="blue_bar"> 
  <span></span> 
  <p id="blue_num"></p> 
 </div> 
 </div> 
</div> 

CSS

使用CSS将页面美化,加载背景图片,确定相对位置等等,你可以直接复制以下代码,在自己的项目中稍作修改即可。

.vote{width:288px; height:220px; margin:60px auto 20px auto;position:relative} 
.votetitle{width:100%;height:62px; background:url(icon.png) no-repeat 0 30px; font-size:15px} 
.red{position:absolute; left:0; top:90px; height:80px;} 
.blue{position:absolute; right:0; top:90px; height:80px;} 
.votetxt{line-height:24px} 
.votetxt span{float:right} 
.redhand{position:absolute; left:0;width:36px; height:36px; background:url(icon.png) no-repeat -1px -38px;cursor:pointer} 
.bluehand{position:absolute; right:0;width:36px; height:36px; background:url(icon.png) no-repeat -41px -38px;cursor:pointer} 
.grayhand{width:34px; height:34px; background:url(icon.png) no-repeat -83px -38px;cursor:pointer} 
.redbar{position:absolute; left:42px; margin-top:8px;} 
.bluebar{position:absolute; right:42px; margin-top:8px; } 
.redbar span{display:block; height:6px; background:red; width:100%;border-radius:4px;} 
.bluebar span{display:block; height:6px; background:#09f; width:100%;border-radius:4px; position:absolute; right:0} 
.redbar p{line-height:20px; color:red;} 
.bluebar p{line-height:20px; color:#09f; text-align:right; margin-top:6px} 

jQuery

当点击手型按钮时,利用jQuery的$.getJSON()向后台php发送Ajax请求,如果请求成功,将会得到后台返回的json数据,jQuery再将json数据进行处理。以下函数:getdata(url,sid),传递了两个参数,url是请求的后台php地址,sid表示当前投票主题ID,我们在该函数中,返回的json数据有红蓝双方的投票数,以及双方比例,根据比例计算比例条的宽度,异步交互展示投票效果。

function getdata(url,sid){ 
 $.getJSON(url,{id:sid},function(data){ 
 if(data.success==1){ 
  var w = 208; //定义比例条的总宽度 
  //红方投票数 
  $("#red_num").html(data.red); 
  $("#red").css("width",data.red_percent*100+"%"); 
  var red_bar_w = w*data.red_percent-10; 
  //红方比例条宽度 
  $("#red_bar").css("width",red_bar_w); 
  //蓝方投票数 
  $("#blue_num").html(data.blue); 
  $("#blue").css("width",data.blue_percent*100+"%"); 
  var blue_bar_w = w*data.blue_percent; 
  //蓝方比例条宽度 
  $("#blue_bar").css("width",blue_bar_w); 
 }else{ 
  alert(data.msg); 
 } 
 }); 
} 

当页面初次加载时,即调用getdata(),然后点击给红方投票或给蓝方投票同样调用getdata(),只是传递的参数不一样。注意本例中的参数sid我们设置为1,是根据数据表中的id设定的,开发者可以根据实际项目读取准确的id。

 $(function(){ 
 //获取初始数据 
 getdata("vote.php",1); 
 //红方投票 
 $(".redhand").click(function(){ 
 getdata("vote.php&#63;action=red",1); 
 }); 
 //蓝方投票 
 $(".bluehand").click(function(){ 
 getdata("vote.php&#63;action=blue",1); 
 }); 
}); 

PHP

前端请求了后台的vote.php,vote.php将根据接收的参数,连接数据库,调用相关函数。

include_once("connect.php"); 

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

if($action=='red'){//红方投票 
vote(1,$id,$ip); 
}elseif($action=='blue'){//蓝方投票 
vote(0,$id,$ip); 
}else{//默认返回初始数据 
echo jsons($id); 
}

函数vote($type,$id,$ip)用来做出投票动作,$type表示投票方,$id表示投票主题的id,$ip表示用户当前ip。首先根据用户当前IP,查询投票记录表votes_ip中是否已经存在当前ip记录,如果存在,则说明用户已投票,否则更新红方或蓝方的投票数,并将当前用户投票记录写入到votes_ip表中以防重复投票。

function vote($type,$id,$ip){ 
 $ip_sql=mysql_query("select ip from votes_ip where vid='$id' and ip='$ip'"); 
 $count=mysql_num_rows($ip_sql); 
 if($count==0){//还没有投票 
 if($type==1){//红方 
  $sql = "update votes set likes=likes+1 where id=".$id; 
 }else{//蓝方 
  $sql = "update votes set unlikes=unlikes+1 where id=".$id; 
 } 
 mysql_query($sql); 
  
 $sql_in = "insert into votes_ip (vid,ip) values ('$id','$ip')"; 
 mysql_query($sql_in); 
 if(mysql_insert_id()>0){ 
  echo jsons($id); 
 }else{ 
  $arr['success'] = 0; 
  $arr['msg'] = '操作失败,请重试'; 
  echo json_encode($arr); 
 } 
 }else{ 
 $arr['success'] = 0; 
 $arr['msg'] = '已经投票过了'; 
 echo json_encode($arr); 
 } 
} 

函数jsons($id)通过查询当前id的投票数,计算比例并返回json数据格式供前端调用。

function jsons($id){ 
 $query = mysql_query("select * from votes where id=".$id); 
 $row = mysql_fetch_array($query); 
 $red = $row['likes']; 
 $blue = $row['unlikes']; 
 $arr['success']=1; 
 $arr['red'] = $red; 
 $arr['blue'] = $blue; 
 $red_percent = round($red/($red+$blue),3); 
 $arr['red_percent'] = $red_percent; 
 $arr['blue_percent'] = 1-$red_percent; 
 
 return json_encode($arr); 
} 

文中还涉及到获取用户真实IP的函数:get_client_ip(),点击这里可以看相关代码:http://www.bitsCN.com/article/58610.htm

MySQL

最后,贴上Mysql数据表,votes表用来记录红蓝双方的投票总数,votes_ip表则用来存放用户的投票IP记录。

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(10) NOT NULL, 
 `vid` int(10) NOT NULL, 
 `ip` varchar(40) NOT NULL 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

PHP+MySql+jQuery实现顶和踩投票功能

本文结合实例,讲解使用PHP+MySql+jQuery实现的“顶”和“踩”投票功能,通过记录用户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&#63;action=like",1); 
 }); 
 //单击“踩”时 
 $("#dig_down").click(function(){ 
 getdata("ajax.php&#63;action=unlike",1); 
 }); 
});

以上内容实现了基于PHP+jQuery+MySql实现红蓝(顶踩)投票代码,希望大家喜欢。

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
優化PHP代碼:減少內存使用和執行時間優化PHP代碼:減少內存使用和執行時間May 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP電子郵件:分步發送指南PHP電子郵件:分步發送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

如何通過PHP發送電子郵件:示例和代碼如何通過PHP發送電子郵件:示例和代碼May 09, 2025 am 12:13 AM

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

高級PHP電子郵件:自定義標題和功能高級PHP電子郵件:自定義標題和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送電子郵件的指南使用PHP和SMTP發送電子郵件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

使用PHP發送電子郵件的最佳方法是什麼?使用PHP發送電子郵件的最佳方法是什麼?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依賴注入的最佳實踐PHP中依賴注入的最佳實踐May 08, 2025 am 12:21 AM

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

PHP性能調整技巧和技巧PHP性能調整技巧和技巧May 08, 2025 am 12:20 AM

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具