Create a Online shop using PHP. And I'm hard stuck on shopping cart

I have to somehow using a button add an item from my database to my shopping cart(Koszyk). I cannot figure out a way to using product ID(maybe?) add it to cart when pressed the button next to item. After few failed attempts I just came it back to this form which just shows all games in shopping cart since each try just made countless errors.



// cart.php?productid=123

class Cart {
 public function __construct(&$storage) {
  $this->storage = $storage;
 }

 public function add(int $productid) : bool {
  $this->storage['cart'][$productid]++;
 }
}

$cart = new Cart($_SESSION);
$cart->add($_GET['productid']);
1 Like
// this is the URL you have to navigate via link or button so the code gets to run when copying this to cart.php file:
// cart.php?productid=123

class Cart {
 // the cart is instanciated when needed and you have to provide where to store data
 public function __construct(&$storage) {
  $this->storage = $storage;
 }

 // just increment a counter that uses the product id as an index so you store a quantity to each unique product
 public function add(int $productid) : bool {
  $this->storage['cart'][$productid]++;
 }
}

// use whenever you need to add something to the cart, may need session_start() if not already done
$cart = new Cart($_SESSION);
$cart->add($_GET['productid']);
1 Like

Might want to also show how to break it down for removing items, decrementing the cart, as I see that being the next question.

1 Like

You need to use a post method form for the ‘add to cart’. By using a link, every time a search engine indexes your site, it will add every item to a cart, and since search engine spiders don’t propagate session id cookies, this will create a new session and a separate session data file for every add to cart link you have on your site.

A post method form should be used for anything that causes an ‘action’ on the server, such as creating, updating, or deleting data.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service