blondievancodelady
blondievancodelady

Reputation: 21

Top item of online shopping cart will not delete?

Building an online store using php and mysql, items in the cart session will all remove just fine with the exception of whatever the top item is. Any ideas? Code for delete from cart:

<?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');
?>

Add to cart:

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;
        }       
    }
?>

I appreciate any help I can get!

Upvotes: 1

Views: 56

Answers (1)

Jaquarh
Jaquarh

Reputation: 6693

It would be much easier to convert your $_SESSION['cart'] to an array rather than joining multiple ID's in a string with separators. You can then use array_filter() and 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;
    });
}

Then to access your cart you can use:

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
}

Which can be used like so:

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 :)
});

Upvotes: 1

Related Questions