How to implement the collection function in PHP: first create the front-end code to implement the login interface; then implement the collection function through the if statement; and finally implement the collection processing function in the PHP background.
Recommended: "PHP Video Tutorial"
php realizes the collection function
This is the database table
Without further ado, 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
<div id="sc" data-id="{$detail.id}" class="in_right"> <p id="sc_words">收藏</p> </div>
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 collection function in php. For more information, please follow other related articles on the PHP Chinese website!