PHP+jQuery+MySql implements red and blue voting examples
This article mainly introduces the example of red and blue voting implemented by PHP jQuery MySql. Interested friends can refer to it. I hope it will be helpful to everyone.
Let me show you the renderings first:
HTML
#We need to display the red and blue sides on the page point of view, as well as the corresponding number and proportion of votes, as well as hand pictures used for voting interaction. In this example, #red and #blue represent the red and blue sides respectively. .redhand and .bluehand are used to make hand-shaped voting buttons, .redbar and .bluebar show the proportion of red and blue, and #red_num and #blue_num show the number of votes from both parties.
<p class="vote"> <p class="votetitle">您对PHP中文网提供的文章的看法?</p> <p class="votetxt">非常实用<span>完全看不懂</span></p> <p class="red" id="red"> <p class="redhand"></p> <p class="redbar" id="red_bar"> <span></span> <p id="red_num"></p> </p> </p> <p class="blue" id="blue"> <p class="bluehand"></p> <p class="bluebar" id="blue_bar"> <span></span> <p id="blue_num"></p> </p> </p> </p>
CSS
Use CSS to beautify the page, load background images, determine relative positions, etc. You can directly copy the following code and use it in your own project Just modify it.
.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
When you click the hand button, use jQuery's $.getJSON() to send an Ajax request to the background php. If the request is successful, you will get the background The json data returned is processed by jQuery. The following function: getdata(url,sid), passes two parameters. URL is the backend PHP address of the request, and sid represents the current voting topic ID. In this function, the json data returned includes the number of votes from both red and blue parties, and The ratio of both parties, calculate the width of the proportion bar based on the ratio, and display the voting effect asynchronously interactively.
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); } }); }
When the page is loaded for the first time, getdata() is called, and then click to vote for the red team or vote for the blue team to also call getdata(), but the parameters passed are different. Note that the parameter sid in this example is set to 1, which is set based on the id in the data table. Developers can read the accurate id based on the actual project.
$(function(){ //获取初始数据 getdata("vote.php",1); //红方投票 $(".redhand").click(function(){ getdata("vote.php?action=red",1); }); //蓝方投票 $(".bluehand").click(function(){ getdata("vote.php?action=blue",1); }); });
PHP
The front end requests the backend vote.php, and vote.php will connect to the database and call related functions based on the received parameters.
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); }
The function vote($type,$id,$ip) is used to make a voting action. $type represents the voting party, $id represents the id of the voting topic, and $ip represents the user's current ip. First, based on the user's current IP, query whether the current IP record already exists in the voting record table votes_ip. If it exists, it means that the user has voted. Otherwise, update the number of votes for the red side or the blue side, and write the current user voting record to the votes_ip table. to prevent repeated voting.
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); } }
The function jsons($id) queries the number of votes for the current id, calculates the proportion and returns the json data format for the front-end call.
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); }
The article also involves the function of obtaining the user’s real IP: get_client_ip(), Click here to see the relevant code: http://www.jb51.net/article/58610.htm
MySQL
Finally, paste the Mysql data table. The votes table is used to record the total number of votes from both red and blue parties, and the votes_ip table is used to store the user’s voting IP records. .
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 implements the "like" and "dislike" voting functions
This article combines examples to explain the "like" and "dislike" voting functions implemented using PHP MySql jQuery. Record the user IP to determine whether the user's voting behavior is valid. This example can also be extended to the voting system.
First we place the "like" and "dislike" buttons on the page, namely #dig_up and #dig_down. The number of votes and the proportion of votes are recorded on the buttons respectively. percentage.
<p class="digg"> <p id="dig_up" class="digup"> <span id="num_up"></span> <p>很好,很强大!</p> <p id="bar_up" class="bar"><span></span><i></i></p> </p> <p id="dig_down" class="digdown"> <span id="num_down"></span> <p>太差劲了!</p> <p id="bar_down" class="bar"><span></span><i></i></p> </p> <p id="msg"></p> </p> $(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); }); });
Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
How to upgrade the MySQL version in phpStudy
PHP implements online calculator function
PHP method to implement asynchronous execution of scripts
The above is the detailed content of PHP+jQuery+MySql implements red and blue voting examples. For more information, please follow other related articles on the PHP Chinese website!

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

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

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











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 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

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.

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.

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 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.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
