Home > Article > Backend Development > How to implement php collection function
# Recommended: "How to implement the php collection function: first create the database table; then create the front-end code to implement the login interface; then implement the collection style through html; finally use php for background processing.
PHP Video Tutorial》
This is the database table
Not much to say, let’s talk about the code
Front desk
<script> $(function(){ $('#sc').click(function(){ var gid=$(this).attr('data-id'); var data={ gid:gid }; $.ajax({ url:"{:U('Goods/collect_add')}", type:"post", data:data, success:function(data){ // window.clearInterval(timer); if(data==1){ window.location.href="{:U('Public/login')}"; //登陆界面 }else { if(data==2){ $('#sc').css({ 'background-color':'white', 'color':'#00ccff', }); $('#sc_words').html( '收藏' ); }else if(data==3){ $('#sc').css({ 'background-color':'#00ccff', 'color':'white', }); $('#sc_words').html( '已收藏' ); }else{ alert(data); } } }, error:function(){ alert('请求失败'); } }); }); })</script>html part
<p id="sc" data-id="{$detail.id}" class="in_right"> <p id="sc_words">收藏</p> </p>PHP background processing
// 商品收藏 1 代表未登录 2代表取消收藏 3 代表 收藏成功 public function collect_add(){ if(empty(session('uid'))){ echo '1'; }else { $collect=M('collect'); $gid=I('post.gid'); //先确定是否已收藏 $map['gid']=$gid; $map['uid']=session('uid'); $data=$collect->where($map)->find(); if($data){ if($data['status']==1){ $collect->where('id='.$data['id'])->setField('status',0); echo '2'; }else{ $collect->where('id='.$data['id'])->setField('status',1); echo '3'; } }else{ if($collect->create()){ $collect->gid=$gid; $collect->create_time=get_date(); $collect->uid=session('uid'); $collect->status=1; $collect->add(); echo '3'; }else{ echo '服务器出错,请重试!'; } } } }
The above is the detailed content of How to implement php collection function. For more information, please follow other related articles on the PHP Chinese website!