How to implement php shopping cart

藏色散人
Release: 2023-02-26 17:20:01
Original
3914 people have browsed it

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,足以满足购物车的要求,同时也
减轻了服务器的负荷
}
Copy after login

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));
}
Copy after login

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数据
Copy after login

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 visit PHP 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template