In a virtual store, for example, the focus is on selling. A user places
things in the cart and for some reason closed the browser. When he
return to this site will have to redo the entire purchase, get the products and
put them in the cart. In this process the user may become impatient
and give up buying. If the site had save the cart
and identify the customer even if it is not logged in, would have greater
chance to realize the sale without bothering it.
I just copied the snippet from another response. The original can be seen here: link
Frizing again, the decision depends on each case. Regardless of the focus being on sales, sometimes saving the cart on database may not be ideal.
I particularly recommend that you save the data even if the user is not authenticated because this data is useful for generating statistics and better understanding the behavior of users. So you can study ways to improve sales. As I mentioned several times, the focus is to sell.
In the technical part, speaking in code, think of 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 $ _SESSION variable you can have other non-cart data as the authenticated user id.
So at least mount something more organized like
$_SESSION['id da loja']['cart'] = array(
'id do produto' => array('nome do produto', 'valor', 'quantidade')
)
If you use the session to authenticate, then mount something like this
$_SESSION['user']['id usuario'] = 'um token'
This will avoid conflicts and allow for flexibility.
But the ideal is to save only one token 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 can allow the user to restore the shopping cart if for some reason they close the browser.