Увеличить количество при добавлении того же товара в сеанс корзины?

На данный момент у меня есть корзина для покупок, которая добавит товар в сеанс корзины. Если в корзину добавляется другой такой же товар, отображаются повторяющиеся товары, количество каждого из которых равно 1.

Что мне нужно добавить / изменить в коде, чтобы обновить количество существующего товара? Вместо добавления повторяющегося элемента.

add_to_cart.php

session_start();

include 'cart.php';
$item_id = $_POST['item_id'];
$qty = $_POST['qty'];
$counter = $_SESSION['counter'];
$cart = new Cart();

if ($counter>0)
{
    $cart = unserialize($_SESSION['cart']);
}
else 
{
    $_SESSION['counter'] = 0;
    $_SESSION['cart'] = "";
}
if (($item_id == "")or ($qty < 1))
{
    header("Location: products.php");
}
else
{
    require_once('conn_db.php');

    $query = "SELECT item_name, price FROM products WHERE (item_id=$item_id)";

    $result = mysql_query($query) or die("Database Error");
    if(mysql_num_rows($result) == 1)
    {
        $price = mysql_result($result, 0,"price");
        $item_name = mysql_result($result, 0, "item_name");

        $new_item = new Item($item_id, $item_name, $qty, $price);
        $cart->add_item($new_item);

        $_SESSION['counter'] = $counter+1;
        $_SESSION['cart'] = serialize($cart);

        header("Location: products.php");
        mysql_close();
    }
    else
    {
        header("Location: products.php");
    }
}   

cart.php

class Item {

    var $item_id;
    var $item_name;
    var $qty;
    var $price;
    var $deleted = false;

    function get_item_cost() {
        return $this->qty * $this->price;
    }

    function delete_item() {
        $this->deleted = true;
    }

    function Item($item_id, $item_name, $qty, $price) {
        $this->item_id = $item_id;
        $this->item_name = $item_name;
        $this->qty = $qty;
        $this->price = $price;
    }

    function get_item_id() {
        return $this->item_id;
    }

    function get_item_name() {
        return $this->item_name;
    }

    function get_qty() {
        return $this->qty;
    }

    function get_price() {
        return $this->price;
    }

}

class Cart {

    var $items;
    var $depth;

    function Cart() {
        $this->items = array();
        $this->depth = 0;
    }

    function add_item($item) {
        $this->items[$this->depth] = $item;
        $this->depth++;
    }

    function delete_item($item_no) {
        $this->items[$item_no]->delete_item();
    }

    function get_depth() {
        return $this->depth;
    }

    function get_item($item_no) {
        return $this->items[$item_no];
    }

}

person BobSacamano    schedule 28.11.2013    source источник
comment
Прежде чем продолжить создание корзины для покупок, прочтите это, затем определенно не пробуйте это $_POST['item_id'] = '1);DROP TABLE products;(', затем прочтите это, затем посмотрите на большое красное предупреждение поле вверху страницы, затем прочтите это.   -  person MLeFevre    schedule 28.11.2013
comment
Я знаю, я ленивый. Он не будет использоваться в реальном мире. Просто школьное задание.   -  person BobSacamano    schedule 28.11.2013


Ответы (2)


Довольно быстрый пример должен направить вас в правильном направлении. Вам нужно будет проверить свой add_item(), чтобы убедиться, что в корзине уже есть товар.

function add_item($item) {
    $item_already_exists = false;
    foreach ($this->items as $depth_id => $item_in_cart) { // loop through the current contents of the cart
        if ($item_in_cart->get_item_id() == $item->get_item_id()) { // if the item already exists in the cart
            $item_already_exists = true;
            $item_exists_at = $depth_id;
            break;
        }
    }

    if ($item_already_exists == true) { //update the existing item
        $this->items[$item_exists_at]->update_qty($item->get_qty());
    } else { // add the new item
        $this->items[$this->depth] = $item;
        $this->depth++;
    }
}

Затем вам нужно будет создать update_quantity() в своем классе Item.

function update_qty($qty) {
    $this->qty += $qty;
}
person MLeFevre    schedule 28.11.2013
comment
Блестяще! Спасибо за помощь. - person BobSacamano; 28.11.2013

Перед добавлением товара проверьте, есть ли он в корзине. Если False, добавьте его. Если True, просто измените количество! :)

person CrisBee21    schedule 28.11.2013