Thinkphp5 + jQuery + Mysql realize voting function

Time:2021-9-20

Thinkphp5 + jQuery + MySQL realizes the voting function. First show you the effect picture. If you feel the effect is good, please refer to the example code.

design sketch:

Front end code:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
< title > realize the red and blue voting function based on thinkphp5 < / Title >
<style type="text/css">
  .vote{width:288px; height:300px; margin:40px auto;position:relative}
  .votetitle{width:100%;height:62px; background:url(/static/index/images/icon.png) no-repeat 0 30px; font-size:15px}
  .red{position:absolute; left:0; top:64px; height:80px;}
  .blue{position:absolute; right:0; top:64px; height:80px;}
  .red p,.blue p{line-height:22px}
  .redhand{position:absolute; left:0;width:36px; height:36px; background:url(/static/index/images/icon.png) no-repeat -1px -38px;cursor:pointer}
  .bluehand{position:absolute; right:0;width:36px; height:36px; background:url(/static/index/images/icon.png) no-repeat -41px -38px;cursor:pointer}
  .grayhand{width:34px; height:34px; background:url(/static/index/images/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}
</style>
<script type="text/javascript" src="/static/index/js/jquery.js"></script>
<script type="text/javascript">
$(function(){
  //Get initial data
  getdata('',1);
  $(".redhand").click(function(){
    getdata("red",1);
  });
  $(".bluehand").click(function(){
    getdata("blue",1);
  });
});
function getdata(type,vid){
  $.ajax({
   url: "{:url('/index/vote/vote')}",
   data: {type:type,vid:vid},
   type:'POST',
   dataType: 'json',
   success: function (res) {
     console.log(res)
     if (res.status == 0) {
       Alert ('successful voting ')
       var w = 208;
      $("#red_num").html(res.msg.rednum);
      $("#red").css("width",res.msg.red_percent*100+"%");
      var red_bar_w = w*res.msg.red_percent-10;
      $("#red_bar").css("width",red_bar_w);
      $("#blue_num").html(res.msg.bluenum);
      $("#blue").css("width",res.msg.blue_percent*100+"%");
      var blue_bar_w = w*res.msg.blue_percent;
      $("#blue_bar").css("width",blue_bar_w);
     }else{
       Alert ('voting failed ');
     }
   }
  });
}
</script>
</head>
<body>
<div>
  <h2>< a href = "// www.jb51. Net / article / 71504. HTM" > thinkphp5 + jQuery + MySQL enables red and blue voting</a></h2>
  <div>
    < div > What do you think of thinkphp5</ div>
    <div>
      <p>Very practical</p>
      <div></div>
      <div>
        <span></span>
        <p></p>
      </div>
    </div>
    <div>
      < P style = "text align: right" > I don't understand at all</p>
      <div></div>
      <div>
        <span></span>
        <p></p>
      </div>
    </div>
  </div>
</div>
</body>
</html>

controller:

<?php
namespace app\index\controller;
use think\Controller;
/**
 *Vote
 */
class Vote extends Controller
{
  /**
   *Front page
   */
  public function index()
  {
    return $this->fetch();
  }
  /**
   *Vote
   * @param vid type ip
   */
  public function Vote()
  {
    $data = input('post.');
    if (!empty($data)) {
      $data['ip'] = get_ ip();  // Get IP
      //First, check whether the current IP has voted
      $count = model('Vote')->checkIp($data);
      //Check whether the type is submitted. If it is submitted, it means that the button is clicked. If it is not submitted, it means that the page is rendered for the first time
      if (!empty($data['type'])) {
        If ($count = = '0') {// I haven't voted yet 
          //Update votes add user IP table
          $res = model('Vote')->postVote($data);
          if ($res) {
            //Voting succeeded in obtaining the current number of votes
            $info = $this->getPercent($data);
            return return_succ($info);
          }else{
            return return_ Error ('voting failed ');
          }
        }else{
          //Already voted
          return return_ Error ('you have voted ');
        }
      }else{
        //Initial rendering, get initial data
        $info = $this->getPercent($data);
        return return_succ($info);
      }
    }else{
      return return_ Error ('data cannot be empty ');
    }
  }
  //Calculation scale
  public function getPercent($data)
  {
    //Voting succeeded in obtaining the current number of votes
    $info = model('Vote')->getInfo($data);
    //Calculation scale 保留3位小数
    $info['red_percent'] = round($info['rednum'] / ($info['rednum'] + $info['bluenum']),3);
    $info['blue_percent'] = 1 - $info['red_percent'];
    return $info;
  }
}

Model:

<?php
namespace app\index\model;
use think\Model;
use think\Db;
class Vote extends Model
{
  //Check whether the current IP has voted
  public function checkIp($data)
  {
    $res = Db::table('votes_ip')->where(['vid'=>$data['vid'],'ip'=>$data['ip']])->count();
    return $res;
  }
  //Vote
  public function postVote($data)
  {
    $info = $this->getInfo($data);
    if ($info) {
      Db::startTrans();
      try {
        if ($data['type'] == "red") {
          //Update the list of votes 
          Db::table('votes')->where(['id'=>$data['vid']])->update(['rednum'=>$info['rednum']+1]);
        }elseif ($data['type'] == "blue") {
          Db::table('votes')->where(['id'=>$data['vid']])->update(['bluenum'=>$info['bluenum']+1]);
        }
        //Add user voting IP
        Db::table('votes_ip')->insert(['vid'=>$data['vid'],'ip'=>$data['ip']]);
        Db::commit();
        return true;
      } catch (Exception $e) {
        Db::rollback();
        return false;
      }
    }
  }
  //Get the current number of votes
  public function getInfo($data)
  {
    //Get their votes
    $info = Db::table('votes')->where(['id'=>$data['vid']])->find();
    return $info;
  }
}

summary

The above is what Xiaobian introduced to you. Thinkphp5 + jQuery + MySQL realizes the voting function. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!