PHP + jQuery + MySql realize the red-blue voting function-PHP source code

Source: Internet
Author: User
We often encounter some voting procedures. Today we have compiled a simple implementation program for the red-blue voting function. If you need to know about such voting, let's see it. we often encounter some voting procedures. Today we have compiled a simple implementation program for the red-blue voting function. If you need to know about such voting, let's see it.

Script ec (2); script

This is a comprehensive knowledge application article that requires you to have basic knowledge about PHP, jQuery, MySQL, html, and css. This article makes appropriate improvements based on the "TOP" and "stepping on" voting functions implemented by PHP + MySql + jQuery and shares data tables. You can click to learn more about this article first.

HTML

We need to show the views of both parties on the red and blue pages, the number and proportion of votes, and the hand images used for voting interaction, in this example, # red and # blue represent the red and blue sides respectively .. The redhand and. bluehand buttons are used for manual voting. The. redbar and. bluebar display the proportional adjustment between the red and blue sides. # red_num and # blue_num display the voting numbers of both sides.


What do you think of the articles provided by Helloweba?


Very practical and hard to understand
















CSS

Use CSS to beautify the page, load the background image, and determine the relative location. You can directly copy the following code and make some modifications in your project.

. 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 () sends an Ajax request to php in the background. If the request succeeds, the json data returned by the background is obtained, and jQuery then processes the json data. The following function: getdata (url, sid) is passed with two parameters. The url is the php address in the request background. sid indicates the ID of the current voting topic. In this function, the returned json data includes the number of votes on both sides of red and blue, and the ratio of both sides. The width of the proportion bar is calculated based on the ratio, and the voting effect is displayed asynchronously.

Function getdata (url, sid ){
$. GetJSON (url, {id: sid}, function (data ){
If (data. success = 1 ){
Var w = 208; // defines the total width of a proportional bar.
// Red-party voting count
$ ("# Red_num" ).html (data. red );
$ ("# Red" ).css ("width", data. red_percent * 100 + "% ");
Var red_bar_w = w * data. red_percent-10;
// The width of the redsquare proportional bar
$ ("# Red_bar" ).css ("width", red_bar_w );
// Number of blue-Party votes
$ ("# Blue_num" ).html (data. blue );
$ ("# Blue" mirror.css ("width", data. blue_percent * 100 + "% ");
Var blue_bar_w = w * data. blue_percent;
// Blue-square proportional Bar Width
$ ("# Blue_bar" ).css ("width", blue_bar_w );
} Else {
Alert (data. msg );
}
});
}

When the page is loaded for the first time, getdata () is called, and getdata () is also called by clicking vote for the red party or vote for the blue party, but the parameters passed are different. Note that the sid parameter in this example is set to 1 Based on the id in the data table. developers can read the exact id based on the actual project.

$ (Function (){
// Obtain the initial data
Getdata ("vote. php", 1 );
// Red party vote
$ (". Redhand"). click (function (){
Getdata ("vote. php? Action = red ", 1 );
});
// Blue-party voting
$ (". Bluehand"). click (function (){
Getdata ("vote. php? Action = blue ", 1 );
});
});

PHP

The frontend requests vote. php In the background. vote. php connects to the database based on the received parameters and calls related functions.

Include_once ("connect. php ");

$ Action = $ _ GET ['action'];
$ Id = intval ($ _ GET ['id']);
$ Ip = get_client_ip (); // obtain the ip address

If ($ action = 'red') {// red party vote
Vote (1, $ id, $ ip );
} Elseif ($ action = 'blue') {// vote by the blue party
Vote (0, $ id, $ ip );
} Else {// The initial data is returned by default.
Echo jsons ($ id );
}

The vote ($ type, $ id, $ ip) function is used to perform a voting action. $ type indicates the voting party, $ id indicates the voting topic id, and $ ip indicates the user's current ip address. First, query whether the current IP address record exists in the votes_ip table based on the user's current ip address. If yes, the user has voted. Otherwise, the red or blue voting count is updated, write the voting records of the current user 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 Square
$ SQL = "update votes set likes = likes + 1 where id =". $ id;
} Else {// blue
$ 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 '] = 'vote passed ';
Echo json_encode ($ arr );
}
}
The jsons ($ id) function is used to query the number of votes of the current id, calculate the proportion, and return 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 ['unlik'];
$ 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 function get_client_ip () is used to obtain the real IP address of a user. Click here to view the relevant code:

// Obtain the user's real IP Address
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, the Mysql DATA table is attached. The votes table is used to record the total number of votes on both sides of red and blue, and the votes_ip table is used to store the user's voting IP address records.

Create table if not exists 'votes '(
'Id' int (10) not null AUTO_INCREMENT,
'Lik' int (10) not null default '0 ',
'Unlik' 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;


Again, if the downloaded demo cannot run, check whether the database connection configuration is correct.

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.