非登陸狀態加入購物車(存入session)
$product_result = queryOne("select name,pic,price,stock from {$prefix}product where id = $product_id");
$cart_result = getSession('cart', 'shop') ? getSession('cart', 'shop') : [];
$add = true;
foreach ($cart_result as $key => $cart) {
if ($cart['proid'] == $product_id) {
$add = false;
$cart['product_count'] = intval($cart['product_count']) + intval($product_count);
$cart_result[$key] = $cart;
}
}
if ($add) {
array_unshift($cart_result, [
'name' => $product_result['name'],
'pic' => $product_result['pic'],
'price' => $product_result['price'],
'stock' => $product_result['stock'],
'product_count' => $product_count,
'proid' => $product_id,
'id' => count($cart_result) + 1,
]);
}
setSession('cart', $cart_result, 'shop');
複製代碼
非登陸轉登陸, session和數據庫進行合併
- 先把session中的數據寫入數據庫
- 而後統一從數據庫裏查數據
$cart_session_result = getSession('cart', 'shop') ? getSession('cart', 'shop') : [];
if($cart_session_result){
deleteSession('cart','shop');
foreach ($cart_session_result as $key => $cart_session) {
add_cart($cart_session['proid'],$cart_session['product_count'],$current_user['id'],$prefix);
}
$cart_session_result = null;
}
$sql = "SELECT {$prefix}product.name, {$prefix}product.id as proid, {$prefix}product.price, {$prefix}product.pic, {$prefix}product.stock, {$prefix}cart.product_count, {$prefix}cart.id FROM {$prefix}product INNER JOIN {$prefix}cart ON {$prefix}cart.product_id = {$prefix}product.id INNER JOIN {$prefix}user ON {$prefix}cart.user_id = {$prefix}user.id where user_id = " . $current_user['id'] . " order by {$prefix}cart.created_at desc";
$cart_result = queryAll($sql);
複製代碼