I found these code, but it doesn't have any explanation.
I don't understand the whole concept or like "how it work".
My conclusion is like this:
1.It GET the "id"
2.Select from database
3.It grab the product and put inside "cart session"
4.Put the session inside array
Is that correct?
This is the full code:
<?php
session_start();
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM products WHERE id=$id");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$product = mysql_fetch_assoc($result);
if (isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
$in_cart = False;
foreach ($cart as &$item) {
if ($item['product']['id'] == $id) {
$item['quantity'] += 1;
$in_cart = True;
break;
}
}
if (!$in_cart) {
$cart[] = array('product' => $product, 'quantity' => 1);
}
} else {
$cart[] = array('product' => $product, 'quantity' => 1);
}
$_SESSION['cart'] = $cart;
?>
I also have some question :
Why this session appear in if condition without ever declared before?
if (isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
What is "&" mean on "&$item"?
foreach ($cart as &$item) {
if ($item['product']['id'] == $id) {
$item['quantity'] += 1;
$in_cart = True;
break;
Why "$cart[] = array('product' => $product, 'quantity' => 1);" appear twice?
if (!$in_cart) {
$cart[] = array('product' => $product, 'quantity' => 1);
}
} else {
$cart[] = array('product' => $product, 'quantity' => 1);
}
$_SESSION['cart'] = $cart;