Home Backend Development PHP Tutorial 基于PHP+jQuery+MySql实现红蓝(顶踩)投票代码_PHP

基于PHP+jQuery+MySql实现红蓝(顶踩)投票代码_PHP

May 30, 2016 am 08:46 AM

先给大家展示效果图:

查看演示 下载源码

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

本文是一篇综合知识应用类文章,需要您具备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> 
Copy after login

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} 
Copy after login

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); 
 } 
 }); 
} 
Copy after login

当页面初次加载时,即调用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); 
 }); 
}); 
Copy after login

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); 
}
Copy after login

函数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); 
 } 
} 
Copy after login

函数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); 
} 
Copy after login

文中还涉及到获取用户真实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; 
Copy after login

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); 
 }); 
});
Copy after login

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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles