Home>Article>Backend Development> How to implement php shopping cart
How is the php shopping cart implemented?
Simple implementation of shopping cart in PHP
First, determine whether to log in,
if(isset($_session['user_id'])){ 存在; 把用户id和商品id,加入购物车表 }else{ 不存在; 使用cookie把商品ID和主机IP放入一个数组 ,把这个数组存入cookie; 浏览器允许存放300个cookie, 每个cookie的大小为4KB,足以满足购物车的要求,同时也 减轻了服务器的负荷 }
If the browser disables cookies, use memcache to implement it
Another method, determine whether to log in,
if(isset($memcache->get('user_id'))){ 存在; 把用户id和商品id,加入购物车表 }else{ 不存在; $memcache = new Memcache(); //实例化memchche $data=['goods_id'=>$goods_id,'ip'=>$_SERVER ['REMOTE_ADDR']]; $memcache->set('key键',serialize($data)); }
There is not much difference between redis implementation and memcache!
memcache code is as follows
$cart=new Cart(); $goods_id = isset($_GET['goods_id']) ? $_GET['goods_id'] : '1'; $session = \yii::$app->session; // $session->set('user_id','1'); $user_id = $session->get("user_id"); $mem = Yii::$app->cache; if(isset($user_id)){ $data['user_id'] = $user_id; $data['goods_id'] = $goods_id; $is_add=$cart->setAttributes($data)->insert(); }else{ $data['user_id'] = $_SERVER['REMOTE_ADDR']; $data['goods_id'] = $goods_id; $mem->set('data',serialize($data)); } unserialize($mem->get('data')); //memcache数据
Both of the above methods can be implemented. If we use the first one, we have to set the cookie expiration time. If we use the second If so, you need to deserialize (unserialize()) when getting the value, and then you can get the data you want!
For more PHP related knowledge, please visitPHP Chinese website!
The above is the detailed content of How to implement php shopping cart. For more information, please follow other related articles on the PHP Chinese website!