In a virtual store, for example, the focus is to sell. A user places
things in the cart and for some reason closed the browser. When it
return on this site will have to redo the entire purchase, fetch the products and
put them in the cart. In this process the user may get impatient
and give up buying. If the site had feature save cart
and identify the customer even if not logged in, would have higher
chance to realize the sale without boring you.
I just copied the excerpt from another reply. The original can see here: /a/119365/4793
Frizando again, the decision depends on each case. Regardless of the focus being for sales, sometimes saving the cart in database may not be ideal.
I particularly recommend saving the data even if the user is not authenticated because this data is useful to generate statistics and better understand the behavior of users. So you can study ways to improve sales. Because as I mentioned several times, the focus is to sell.
In the technical part, speaking of codes, think about how to assemble the structure.
Avoid weak or messy things like
$_SESSION = array(
'id do produto' => array('nome do produto', 'valor', 'quantidade')
)
Because in the global variable $_SESSION can have other data not referring to the cart as the id of the authenticated user.
So at least build something more organized like
$_SESSION['id da loja']['cart'] = array(
'id do produto' => array('nome do produto', 'valor', 'quantidade')
)
if you use Session to authenticate, then mount something like this
$_SESSION['user']['id usuario'] = 'um token'
This will avoid conflict and allow flexibility.
But the ideal is to save only one token also to the Cart.
$_SESSION['id da loja']['cart'] = 'token do cart';
This token would then be related to a table in the database
tabela cart
id_loja
id_usuario
cart_token
tabela cart_items
id_item
item_valor
item_quantidade
id_qualquer_outra_coisa_que_precisar
But instead of using Session to save the token, use cookie
$_COOKIE['id da loja']['cart'] = 'token do cart';
as mentioned above, using the cookie, you may allow the user to restore the shopping cart if for some reason you close your browser.
You can use Session to keep products in the user’s shopping cart. Session in PHP usually contains your session data like Name and login, but it can also contain data of other things. It is not convenient to put too much pressure on Session. But for a shopping cart it is perfect.
– Jorge B.