PHP, MySql, jQuery implement 'like' and 'dislike' voting functions

WBOY
Release: 2016-07-25 08:55:30
Original
828 people have browsed it
  1. CREATE TABLE IF NOT EXISTS `votes` (
  2. `id` int(10) NOT NULL AUTO_INCREMENT,
  3. `likes` int(10) NOT NULL DEFAULT '0',
  4. `unlikes` int(10) NOT NULL DEFAULT '0',
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  7. INSERT INTO `votes` (`id`, `likes`, `unlikes`) VALUES
  8. (1, 30, 10);
  9. CREATE TABLE IF NOT EXISTS `votes_ip` (
  10. `id` int(10) NOT NULL,
  11. `vid` int(10) NOT NULL,
  12. `ip` varchar(40) NOT NULL
  13. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Copy code

2, html page part On the page, there are two buttons that represent "like" and "dislike" respectively, namely #dig_up and #dig_down. The number of votes and their respective percentages are recorded on the buttons, making it very intuitive to compare the voting results.

  1. < ;p>Very good, very powerful!

  • Too bad!

  • Copy code

    3, css code part You must use CSS to beautify the page, use a picture called diggs.png to position different button backgrounds, and set position to position the positional relationship between each element.

    1. .digg{width:420px; height:120px; margin:80px auto 20px auto; position:relative}
    2. #dig_up,#dig_down{width:200px; height:48px; margin:10px; position:relative} ;
    3. border:1px solid #d3d3d3; padding-left:42px; cursor:pointer}
    4. .digup{background:url(diggs.png) no-repeat 4px 2px;}
    5. .digup_on{background:url(diggs.png) no-repeat 4px -49px;}
    6. .digdown{background:url(diggs.png) no-repeat 4px -102px;}
    7. .digdown_on{background:url(diggs.png) no-repeat 4px -154px;}
    8. # num_up,#num_down{position:absolute; right:6px; top:18px; font-size:20px;}
    9. #dig_up p{height:24px; line-height:24px; color:#360}
    10. #dig_down p{height :24px; line-height:24px; color:#f30}
    11. .bar{width:100px; height:12px; line-height:12px; border:1px solid #f0f0f0;
    12. position:relative; text-align:center}
    13. .bar span{display:block; height:12px; }
    14. .bar i{position:absolute; top:0; left:104px;}
    15. #bar_up span{background:#360}
    16. #bar_down span{background:# f60}
    17. #msg{position:absolute; right:20px; top:40px; font-size:18px; color:#f00}
    Copy code

    2, jquery part This example also relies on jQuery, so you must not forget to load the jquery library file in the page first. First, jQuery needs to process the background images that change when the mouse slides over the two voting buttons respectively, which is achieved through addClass() and removeClass().

    1. $(function(){
    2. //Change the background style when the mouse slides towards and away from the voting button
    3. $("#dig_up").hover(function(){
    4. $(this).addClass( "digup_on");
    5. },function(){
    6. $(this).removeClass("digup_on");
    7. });
    8. $("#dig_down").hover(function(){
    9. $(this). addClass("digdown_on");
    10. },function(){
    11. $(this).removeClass("digdown_on");
    12. });
    13. //Initialize data
    14. getdata("do.php",1);
    15. //When clicking "Like"
    16. $("#dig_up").click(function(){
    17. getdata("do.php?action=like",1);
    18. });
    19. //Click "
    20. $("#dig_down").click(function(){
    21. getdata("do.php?action=unlike",1);
    22. });
    23. });
    Copy code

    Then, initialize the data, that is, after the page is loaded, the initial voting results should be displayed, including the number of votes and the percentage. Write the operation of obtaining data in a custom function getdata(), and complete the loading of data by passing different request addresses and id parameters. In the function getdata(), an ajax request is sent to the URL. According to the return result of the background processing, if the vote is successful, the corresponding element content in the page will be changed, including the number of votes and the percentage.

    1. function getdata(url,sid){
    2. $.getJSON(url,{id:sid},function(data){
    3. if(data.success==1){//The vote was successful
    4. $( "#num_up").html(data.like);
    5. //Display the percentage progress bar effect by controlling the width
    6. $("#bar_up span").css("width",data.like_percent);
    7. $(" #bar_up i").html(data.like_percent);
    8. $("#num_down").html(data.unlike);
    9. $("#bar_down span").css("width",data.unlike_percent);
    10. $("#bar_down i").html(data.unlike_percent);
    11. }else{//Vote failed bbs.it-home.org
    12. $("#msg").html(data.msg).show( ).css({'opacity':1,'top':'40px'})
    13. .animate({top:'-50px',opacity:0}, "slow");
    14. }
    15. });
    16. }
    Copy code

    4, php code part The acquisition of data is completed through do.php. Do.php connects to the database according to the parameters passed by the front-end page, and enters the "top", "dislike" and initial data processing modules according to the conditions. The following is the do.php module code structure:

    1. include_once("connect.php");//Connect to the database
    2. $action = $_GET['action'];
    3. $id = 1;
    4. $ip = get_client_ip() ;//Get ip
    5. if($action=='like'){//Like
    6. likes(1,$id,$ip);
    7. }elseif($action=='unlike'){//Dislike
    8. likes(0,$id,$ip);
    9. }else{
    10. echo jsons($id);
    11. }
    Copy code

    The function likes() is used to handle the "like" and "dislike" voting modules , the first step is to determine whether the user IP has already voted. If the user IP has voted, the corresponding prompt will be returned directly. If the user IP has no voting record, the votes table will be updated, the corresponding vote number will be increased by 1, and then the user's IP will be inserted into the votes_ip table. Record, if the operation is successful, call jsons() to output data such as the number of votes and percentage after voting, otherwise enter a prompt message indicating that the operation failed.

    1. function likes($type,$id,$ip){
    2. $ip_sql=mysql_query("select ip from votes_ip where vid='$id' and ip='$ip'" );
    3. $count=mysql_num_rows($ip_sql);
    4. if($count==0){//Not liked yet
    5. if($type==1){//Liked
    6. $sql = "update votes set likes =likes+1 where id=".$id;
    7. }else{//dislike
    8. $sql = "update votes set unlikes=unlikes+1 where id=".$id;
    9. }
    10. mysql_query($sql);
    11. $sql_in = "insert into votes_ip (vid,ip) values ​​('$id','$ip')";
    12. mysql_query($sql_in);
    13. if(mysql_insert_id()>0){
    14. echo jsons( $id);
    15. }else{
    16. $arr['success'] = 0;
    17. $arr['msg'] = 'Operation failed, please try again';
    18. echo json_encode($arr);
    19. }
    20. }else {
    21. $msg = $type==1?'You have liked':'You have disliked';
    22. $arr['success'] = 0;
    23. $arr['msg'] = $msg;
    24. echo json_encode($arr);
    25. }
    26. }
    Copy code

    The function jsons() is used to read the number of votes for the corresponding id in the votes table, calculate the percentage, and finally output this information in json format , for use by front-end pages.

    1. function jsons($id){
    2. $query = mysql_query("select * from votes where id=".$id);
    3. $row = mysql_fetch_array($query);
    4. $ like = $row['likes'];
    5. $unlike = $row['unlikes'];
    6. $arr['success']=1;
    7. $arr['like'] = $like;
    8. $arr[' unlike'] = $unlike;
    9. $like_percent = round($like/($like+$unlike),3)*100;
    10. $arr['like_percent'] = $like_percent.'%';
    11. ​​$arr['unlike_percent '] = (100-$like_percent).'%';
    12. ​​
    13. return json_encode($arr);
    14. }
    Copy code

    This example can be applied to common "like", agree and disagree comments, In scenarios such as voting systems, front-end and back-end interactive functions implemented using Ajax principles are used. There is also a function get_client_ip() in do.php to obtain the user’s real IP. In the source code package provided in this article, you can download it and study it.



    source:php.cn
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!