PHP+jQuery+MySql实现红蓝投票功能
我们经常会碰到一些投票程序了,今天小编整理了一个简单的红蓝投票功能的实现程序了,有需要了解这种投票的朋友进入来看看吧.
本文是一篇综合知识应用类文章,需要您具备PHP、jQuery、MySQL以及html和css方面的基本知识。本文在《PHP+MySql+jQuery实现的“顶”和“踩”投票功能》一文基础上做了适当改进,共用了数据表,您可以先点击了解这篇文章。
HTML
我们需要在页面中展示红蓝双方的观点,以及对应的投票数和比例,以及用于投票交互的手型图片,本例以#red和#blue分别表示红蓝双方。.redhand和.bluehand用来做手型投票按钮,.redbar和.bluebar展示红蓝双方比例调,#red_num和#blue_num展示双方投票数。
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?action=red",1);
});
//蓝方投票
$(".bluehand").click(function(){
getdata("vote.php?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(),点击这里可以看相关代码:
//获取用户真实IP
function getIp() {
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else
if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else
if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else
if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return ($ip);
}
最后,贴上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;
再次提醒,下载的demo如果运行不了,请先检查数据库连接配置是否正确

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

TheFiiOCP13cassetteplayerwasannouncedinJanuary.Now,FiiOisexpandingitsportfoliowithtwonewmodels-onewitharedfrontandonewithatransparentfront.Thelatternotonlyperfectlymatchestheretrocharmoftheangulardesign,butalso

The rapid development of blockchain technology has brought about the need for reliable and efficient analytical tools. These tools are essential to extract valuable insights from blockchain transactions in order to better understand and capitalize on their potential. This article will explore some of the leading blockchain data analysis tools on the market, including their capabilities, advantages and limitations. By understanding these tools, users can gain the necessary insights to maximize the possibilities of blockchain technology.

You can easily cancel AppleOne (like AppleOne) subscriptions, as well as third-party AppStore subscriptions, on your iPhone, iPad, or Mac. Apple offers a variety of services that Apple device owners can subscribe to, including AppleMusic, AppleTV+, AppleArcade, iCloud+, AppleNews+, and AppleFitness+. It also offers these services as a bundled subscription called Apple One. Apple in March 2023 made significant price increases for several of its services, including Apple TV+, Apple Arcade and

The latest feature update for Windows 11 is here, and it brings various app updates and improvements, however, many people are reporting that Windows 1123H2 does not have Copilot. This is unfortunate, especially if you're looking forward to trying out new AI assistants. We at Windows Report have encountered the same problem, and in today's guide we will show you some potential solutions that may help if Windows 11 Copilot is missing. How to enable Copilot on 23H2? How do we test, review and score? Over the past 6 months, we have been working hard to establish a new review system for how we produce content. use it

Hello everyone, I am your old friend, a friend who talks to you about the crypto market in Binance Plaza all year round. Binance Launchpool recently launched the 64th phase project - RedStone (RED). As a multi-chain oracle project, it sparked a lot of discussion before it was launched. Today we will have an in-depth analysis of RED to see how its potential and how the price may go after it is launched. Binance Launchpool No. 64 project analysis and price forecast: Can RedStone (RED) ignite the market? Project background and core highlights RedStone (RED) is a multi-chain oracle platform focusing on decentralized finance (DeFi), with the goal of E

Web3 Vertical AIAgent: Subvert tradition and reshape the industry landscape? This paper discusses the application differences of AIAgent in Web2 and Web3 and the future potential of Web3Agent. Web2 has been widely used to improve efficiency, covering sales, marketing and other fields, and has achieved significant economic benefits. Web3Agent combines blockchain technology to open up new application scenarios, especially in the DeFi field. It demonstrates potential beyond Web2Agent through token incentives, decentralized platforms and on-chain data analysis. Although Web3Agent is currently facing challenges, its unique advantages make it expected to compete with Web2 in the medium and long term, and even reshape the industry landscape. Web2AI
