Верхний элемент интернет-магазина не удалится? - PullRequest
0 голосов
/ 12 ноября 2018

При создании интернет-магазина с использованием 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 голосов
/ 12 ноября 2018

Было бы намного проще преобразовать $_SESSION['cart'] в массив, чем объединять несколько идентификаторов в строку с разделителями. Затем вы можете использовать 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 :)
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...