Php+jquery+mysql to achieve red and blue voting function

Source: Internet
Author: User
Tags get ip json relative

This article is a comprehensive knowledge application class that requires you to have basic knowledge of PHP, JQuery, MySQL, and HTML and CSS. This article in the "Php+mysql+jquery implementation of the" Top and "step" voting function on the basis of a proper improvement, a total of data tables, you can click to understand this article.

Html

We need to show the views of both red and blue on the page, as well as the corresponding number and proportion of votes, as well as hand-shaped pictures for the interactive voting, in this case the red and blue sides are #red and #blue respectively. Redhand and. Bluehand are used to make hand voting buttons,. Redbar and. Bluebar Show the proportion of red and blue, #red_num和 #blue_num show both sides of the vote.

<div class= "Vote" >
<div class= "Votetitle" > What do you think of the articles provided by Helloweba? </div>
<div class= "Votetxt" > very practical <span> completely read </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

Use CSS to beautify the page, load the background image, determine the relative position, etc., you can directly copy the following code, in your own project slightly 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 the hand button is clicked, use jquery's $.getjson () to send AJAX requests to the backstage PHP, and if the request succeeds, it will get the JSON data back in the background and jquery will then process the JSON data. The following function: GetData (URL,SID), passed two parameters, URL is the requested background PHP address, Sid represents the current voting topic ID, we in this function, the return of the JSON data have the red and blue votes, as well as the ratio of both sides, according to the proportional ratio of the width of the bar, The asynchronous interaction shows the voting effect.

function GetData (URL,SID) {
$.getjson (url,{id:sid},function (data) {
if (data.success==1) {
var w = 208; Define the total width of the scale bar
Voting number of Red Square
$ ("#red_num"). HTML (data.red);
$ ("#red"). CSS ("width", data.red_percent*100+ "%");
var red_bar_w = w*data.red_percent-10;
Red Square ratio bar width
$ ("#red_bar"). CSS ("width", red_bar_w);
Number of blue-side votes
$ ("#blue_num"). HTML (data.blue);
$ ("#blue"). CSS ("width", data.blue_percent*100+ "%");
var blue_bar_w = w*data.blue_percent;
Blue side ratio bar width
$ ("#blue_bar"). CSS ("width", blue_bar_w);
}else{
alert (data.msg);
}
});
}

When the page is first loaded, call GetData (), and then click on the red party to vote or give the blue vote the same call GetData (), just passing the parameters are different. Note that the parameter SID in this example is set to 1, based on the ID in the datasheet, and the developer can read the exact ID based on the actual project.

$ (function () {
Get Initial data
GetData ("vote.php", 1);
Red Party vote
$ (". Redhand"). Click (function () {
GetData ("vote.php?action=red", 1);
});
Blue Side vote
$ (". Bluehand"). Click (function () {
GetData ("Vote.php?action=blue", 1);
});
});

Php

The front-end request vote.php,vote.php will connect the database according to the received parameters, and call the related function.

Include_once ("connect.php");

$action = $_get[' action '];
$id = Intval ($_get[' id '));
$ip = Get_client_ip ();//Get IP

if ($action = = ' Red ') {//Red side vote
Vote (1, $id, $IP);
}elseif ($action = = ' Blue ') {//blue vote
Vote (0, $id, $IP);
}else{//Default return initial data
echo jsons ($id);
}

The function vote ($type, $id, $IP) is used to make a voting action, $type represents the voter, $id the ID of the voting subject, $IP represents the user's current IP. First, according to the user's current IP, query polling record table votes_ip whether the current IP record exists, if it exists, the user has voted, or update red or blue side of the vote, and 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) {//No vote yet
if ($type ==1) {//Red side
$sql = "Update votes set likes=likes+1 where id=". $id;
}else{//Blue Square
$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 '] = ' operation failed, please try again ';
echo Json_encode ($arr);
}
}else{
$arr [' success '] = 0;
$arr [' msg '] = ' already voted ';
echo Json_encode ($arr);
}
}
The function jsons ($id) calculates the proportions and returns the JSON data format for front-end calls by querying the polling number of the current ID.

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 obtaining the user's real IP function: get_client_ip (), click here to see the relevant code:

Get user Real 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);
}


Finally, put on the MySQL data table, votes table used to record the total number of red and blue votes, votes_ip table is used to hold the user's voting IP records.

CREATE TABLE IF not EXISTS ' votes ' (
' ID ' int (a) not NULL auto_increment,
' Likes ' int (a) not NULL DEFAULT ' 0 ',
' Unlikes ' int (a) 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 (a) not NULL,
' Vid ' int (a) not NULL,
' IP ' varchar not NULL
) Engine=myisam DEFAULT Charset=utf8;


Again, download the demo if not run, please check the database connection configuration is correct

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.