在线购物车的首项不会删除吗?

时间:2018-11-12 18:37:30

标签: php session

使用php和mysql建立在线商店,购物车会话中的所有项目都将被删除,除了最重要的项目。有任何想法吗? 从购物车中删除的代码:

<?php 
session_start();
    $items = $_SESSION['cart'];
    $cartitems = explode(",", $items);
        if(isset($_GET['remove']) && !empty($_GET['remove'])){
        $delitem = $_GET['remove'];
        unset($cartitems[$delitem]);
        $itemids = implode(",", $cartitems);
        $_SESSION['cart'] = $itemids;
    }
header('location:cart.php');
?>

添加到购物车:     

session_start();
if(isset($_GET['id']) & !empty($_GET['id'])){
    if(isset($_SESSION['cart']) && !empty($_SESSION['cart'])){

        $items = $_SESSION['cart'];
        $cartitems = explode(",", $items);
            $items .= "," . $_GET['id'];
            $_SESSION['cart'] = $items;     

        }else{
            $items = $_GET['id'];
            $_SESSION['cart'] = $items;
        }       
    }
?>

感谢您能提供的任何帮助!

1 个答案:

答案 0 :(得分:1)

将您的$_SESSION['cart']转换为数组比将多个ID插入带有分隔符的字符串中要容易得多。然后,您可以使用array_filter()array_search()

public function addItemToCart($id) {
    # Filter through cart for the ID
    $cartProduct = array_filter($_SESSION['cart'], function($product) use($id) {
        $product = (object) $product;
        return (int) $product->id == (int) $id;
    });

    # If the ID exists, increase quantity
    if (!empty($cartProduct)) {
        $product = (object) $cartProduct[0];
        ++$_SESSION['cart'][array_search(
        (int) $product->id,
        $_SESSION['cart'])]['quantity'];
        return;
    }

    # If the ID does not exist, add new ID
    $_SESSION['cart'][] = ['id' => $id, 'quantity' => 1];
}

function removeItemFromCart($id) {
    # Update cart with the removed item
    $_SESSION['cart'] = array_filter($_SESSION['cart'], function($product) {
        $product = (object) $product;
        return (int) $product->id != (int) $id;
    });
}

然后可以使用以下方式访问购物车:

function getItemsFromCart($callback) {
    if(!is_callable($callback)) return false; # Ensure it is a Closure
    foreach($_SESSION['cart'] as $product) call_user_func($callback, (object) $product); # Pass every array as an object to the function
}

可以像这样使用:

getItemsFromCart(function($product) {
    # $product will be used for every product inside the cart with ->id and ->quantity
    # Recommend making this a static call to get a connection rather than opening multiple - just demonstration purposes.

    $stmt = (new PDO('dsn', 'user', 'pass', [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false
    ]))->Prepare('SELECT cost FROM myProductTable WHERE productId = ? LIMIT 1');

    $stmt->execute(array((int) $product->id));
    $cost = ((object) $stmt->fetch())->cost * (int) $product->quantity; # Here is your cost :)
});