Why is the current data being overwritten every time I try to add something to the array?

Viewed 40

I am currently trying to handle a shopping cart object for a website using PHP. I have the Shopping Cart object persisting across multiple web pages.

Whenever I add something to the cart, I first check to see if the object exists, and if it doesn't exist, I will add it to the array of items, but if it does exist, I will simply update the quantity on the existing item.

However this is not the case. Whenever I try to add something to the cart, my program is having troubles recognizing that an object is already in the cart. In addition, if something is not in the cart, it will add it to the cart, however it will remove what is already inside of it and add then replace.

Below you can find the code where I check for it's existence and add it:

    public function obj_exists($item_id){
        for($i=0;$i<$this->count;$i++){
            if($this->items[$i]->getID()==(int)$item_id){
                return $i;
            }
        }
        return -1;
    }
    
    public function addToCart($item_id, $quantity){
        $existing=$this->obj_exists($item_id);
        echo $existing;
        if(is_numeric($item_id) && is_numeric($quantity) && $quantity>=1){
            if($existing==-1){  
                $newItem=new CartItem();
                $newItem->setQuant($quantity);
                $newItem->setID($item_id);
                $this->items[]=$newItem;
                $this->count++;
            } else {
                $this->items[$existing]->increment();
            }
        } else if (is_numeric($item_id) && is_numeric($quantity)) {
            echo "Invalid quantity";
        }
    }

Here is where I call the addToCart method in my cart_handler.php:

$serialized=$_SESSION['user_cart'];
$cartobj=new ShoppingCart();
$cartobj->__unserialize($serialized);
$cartobj->addToCart($new_item_id, 1);

$_SESSION['user_cart']=$cartobj->__serialize();
header('Location: http://localhost/website/heroku/order.php');
exit();

And just in case anyone asks, here is my serialization and unserialization methods:

    public function serialize_items() {
        $serialized=array();
        foreach($this->items as $item) {
            $serialized[]=$item->__serialize();
        }
        return $serialized;
    }

    public function __serialize() {
        return [
            'count'=>$this->count,
            'items'=>$this->serialize_items()
        ];
    }

    public function unserialize_items(array $data) {
        $unserialized=array();
        foreach($data as $item){
            $tmpItem=new CartItem();
            $tmpItem->unserialize($item);
            $unserialized[]=$tmpItem;
        }
        return $unserialized;
    }

    public function __unserialize(array $data) {
        $this->count=$data[0];
        if(!is_null($data[1])){
            $this->items=$this->unserialize_items($data[1]);
        }
    }
0 Answers
Related