draw.php <?php /** * Created by PhpStorm. * User: user * Date: 2016/11/14 0014 * Time: 上午 8:48 */ ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="jquery-3.0.0.min.js"></script> </head> <body> <div> <span id="span1">雙十一抽優惠券<button id="b_1">試試手氣</button></span><br/> <span id="span2"></span> </div> </body> <script> $(function () { $('#b_1').click(function(){ $.get('draw_do.php',{u_id:1},function (msg) { //沒做登錄表單,所以就傳個1表示用戶 if(msg==1) { $('#span2').text('你獲取了一張優惠券 滿100減50'); }else if(msg==2) { $('#span2').text('你獲取了一張優惠券 滿100減30'); }else if(msg==3) { $('#span2').text('你獲取了一張優惠券 滿100減20'); }else if(msg==4) { $('#span2').text('你獲取了一張優惠券 滿100減10'); }else if(msg==5) { $('#span2').text('未中獎'); }else{ $('#span2').text(msg); $('#span1').html("雙十一抽優惠券 <span>倆次機會已經用完</span>") } }) }) }) </script> </html> draw_do.php
<?php /** * Created by PhpStorm. * User: user * Date: 2016/11/14 0014 * Time: 上午 9:15 */ $pro=array(1=>5,2=>10,3=>20,4=>45,5=>100); function get_rand($pro) { $res=''; $pro_num=array_sum($pro); foreach ($pro as $key=>$value) { $rand_num=mt_rand(0,$pro_num); if ($rand_num<=$value) { $res=$key; break; }else{ $pro_num-=$value; } } unset($pro); return $res; } $u_id=$_GET['u_id']; $pdo=new PDO("mysql:host=localhost;dbname=ten","root","root"); $pdo->exec("set names utf8"); $sql1="select * from draw_user where u_id=$u_id"; $arr=$pdo->query($sql1)->fetch(PDO::FETCH_ASSOC); //var_dump($arr);die; if ($arr['status']==2) { $sql2="select * from draw where d_id=".$arr['d_id']." "; $data=$pdo->query($sql2)->fetch(PDO::FETCH_ASSOC); echo "你獲取了一張優惠券 ".$data['d_name']; die; }else{ $d_id=get_rand($pro); if ($arr) { $sql2="update draw_user set d_id=$d_id,status=2 where u_id=$u_id"; $pdo->exec($sql2); }else{ $sql2="insert into draw_user (d_id,u_id,status) values($d_id,$u_id,1)"; $pdo->exec($sql2); } echo $d_id; }
mysql數據表:
draw:d_id int (11)主鍵自增 d_name varchar(32) 數據:
1 滿100減50
2 滿100減30
3 滿100減20
4 滿100減10
5 未中獎(概率
draw_user.php
d_id int(11)
u_id int(11)
status smallint(2) 默認0
無數據