I'm fairly new to PHP and I'm trying to build a small shopping cart class and it seems I'm falling over at the first hurdle 😕
I have 2 classes, the intention being that I have a 'Shopping Cart' which contains a list of 'Products'.
class Product {
public $productid, $name, $qty, $price;
public function __construct($iProductID, $iName, $iQty, $iPrice) {
$this->productid = $iProductID;
$this->name = $iName;
$this->qty = $iQty;
$this->price = $iPrice;
}
public function value() {
return $this->price * $this->qty;
}
}
class ShoppingCart {
public $products;
function add_product($product_id, $qty) {
$result = mysql_query("SELECT * FROM products WHERE productid = ".SQL::quote($product_id));
if ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$this->products[] = New Product($product_id, $row['title'], $qty, $row['price']);
}
}
function remove_product($product_id) {
foreach ($this->products as $key => $product) {
if ($product->productid == $product_id) {
unset($this->products[$key]);
}
}
}
public function cartValue() {
$total = 0;
foreach ($this->products as &$product) {
$total += $product->value();
}
return $total;
}
} // end of class
and I'm using it as follows:
$cart = $_SESSION['CART'];
if (!isset($cart)) $cart = new ShoppingCart();
$cart->add_product(1,2);
//$cart->remove_product(1);
foreach ($cart->products as &$product) {
echo($product->productid . "<br />");
echo($product->name . "<br />");
echo($product->price . "<br />");
echo($product->qty . "<br />");
echo($product->value() . "<br /><br />");
}
echo $cart->cartValue();
$_SESSION['CART'] = $cart;
The shopping cart needs to be saved and retrieved from the session.
I've been testing it by 'adding' and 'removing' products, and even the add doesn't seem to work.
If I blank the session, and run the script once, it should add 1 product, and print it to the screen. It does this.
If I then comment out the add product line, and run the script again I expect it to load the shopping cart from the session and just print out the one product that's already been added. Instead, it prints out two copies of the same product.
There's a problem somewhere when storing it to the session because it seems to be making two copies of every product.
This is what is shown on the second refresh (I have commented out the 'add' at this point)
1
6x4 picture
2.99
2
5.98
1
6x4 picture
2.99
2
5.98
11.96
Like I said I'm pretty new at this so any advice and any pointers would be much appreciated.