Home  >  Article  >  Backend Development  >  How to implement "like" and "dislike" voting functions using php+jQuery

How to implement "like" and "dislike" voting functions using php+jQuery

墨辰丷
墨辰丷Original
2018-06-01 09:48:111140browse

This article combines examples to explain the "like" and "dislike" voting functions implemented using PHP MySql jQuery to determine whether the user's voting behavior is valid.

When we browse the web and we want to agree or disagree with the web content such as articles and comments, we can vote by clicking "Like" and "Dislike" on the web page. Developers can implement the entire interaction process asynchronously through ajax, thereby improving user experience.

We first need to prepare the mysql data table required for the entire instance to run. The instance requires two tables. The votes table is used to record the number of user votes for corresponding articles or comments, and by default we write an id of The data of 1 is used for demonstration. The votes_ip table is used to record the IP of each user's vote. The program determines whether the vote is valid based on the user's IP.

Data table

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;

HTML

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

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

CSS

We must use CSS to beautify the page, we use a picture diggs. png to position different button backgrounds, and position the positional relationship between each element by setting position.

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

jQuery

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

$(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("do.php",1); 
  
 //单击“顶”时 
 $("#dig_up").click(function(){ 
  getdata("do.php?action=like",1); 
 }); 
 //单击“踩”时 
 $("#dig_down").click(function(){ 
  getdata("do.php?action=unlike",1); 
 }); 
});

Then, we initialize the data, that is, after the page is loaded, we need to display the initial voting results, including the number of votes and the percentage. . We 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.

function getdata(url,sid){ 
 $.getJSON(url,{id:sid},function(data){ 
  if(data.success==1){//投票成功 
   $("#num_up").html(data.like); 
   //通过控制宽度来显示百分比进度条效果 
   $("#bar_up span").css("width",data.like_percent); 
   $("#bar_up i").html(data.like_percent); 
   $("#num_down").html(data.unlike); 
   $("#bar_down span").css("width",data.unlike_percent); 
   $("#bar_down i").html(data.unlike_percent); 
  }else{//投票失败 
   $("#msg").html(data.msg).show().css({&#39;opacity&#39;:1,&#39;top&#39;:&#39;40px&#39;}) 
   .animate({top:&#39;-50px&#39;,opacity:0}, "slow"); 
  } 
 }); 
}

PHP

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

include_once("connect.php");//连接数据库 
 
$action = $_GET[&#39;action&#39;]; 
$id = 1; 
$ip = get_client_ip();//获取ip 
 
if($action==&#39;like&#39;){//顶 
 likes(1,$id,$ip); 
}elseif($action==&#39;unlike&#39;){//踩 
 likes(0,$id,$ip); 
}else{ 
 echo jsons($id); 
}

Function likes() is used to handle the "like" and "dislike" voting modules. First, it determines whether the user IP has already voted. If it has already voted, it will directly return the corresponding prompt. If If the user IP has no voting record, update the votes table, add the corresponding vote number by 1, and then insert the user's IP record into the votes_ip table. If the operation is successful, call jsons() to output the number of votes and percentage after voting, etc. data, otherwise the input operation fails.

function likes($type,$id,$ip){ 
 $ip_sql=mysql_query("select ip from votes_ip where vid=&#39;$id&#39; and ip=&#39;$ip&#39;"); 
 $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 (&#39;$id&#39;,&#39;$ip&#39;)"; 
  mysql_query($sql_in); 
   
  if(mysql_insert_id()>0){ 
   echo jsons($id); 
  }else{ 
   $arr[&#39;success&#39;] = 0; 
   $arr[&#39;msg&#39;] = &#39;操作失败,请重试&#39;; 
   echo json_encode($arr); 
  } 
 }else{ 
  $msg = $type==1?&#39;您已经顶过了&#39;:&#39;您已经踩过了&#39;; 
  $arr[&#39;success&#39;] = 0; 
  $arr[&#39;msg&#39;] = $msg; 
  echo json_encode($arr); 
 } 
}

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

function jsons($id){ 
 $query = mysql_query("select * from votes where id=".$id); 
 $row = mysql_fetch_array($query); 
 $like = $row[&#39;likes&#39;]; 
 $unlike = $row[&#39;unlikes&#39;]; 
 $arr[&#39;success&#39;]=1; 
 $arr[&#39;like&#39;] = $like; 
 $arr[&#39;unlike&#39;] = $unlike; 
 $like_percent = round($like/($like+$unlike),3)*100; 
 $arr[&#39;like_percent&#39;] = $like_percent.&#39;%&#39;; 
 $arr[&#39;unlike_percent&#39;] = (100-$like_percent).&#39;%&#39;; 
  
 return json_encode($arr); 
}

This example can be applied to common "like", agree and disagree comments, voting systems and other scenarios, implemented using Ajax principles Front-end and back-end interaction functions. There is also a function get_client_ip() in do.php to obtain the user's real IP.

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php Processing method for obtaining xml interface data

phpSeveral ways to get the id of the data just inserted

phpMethods to encapsulate the mysql class based on singleton mode

The above is the detailed content of How to implement "like" and "dislike" voting functions using php+jQuery. For more information, please follow other related articles on the PHP Chinese website!

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