Quote:
I've learnt about cookies and sessions, and I'd like to know - which one do you use for a shopping cart?
|
Cookies transmit the cookie data to and from the browser every time a request is made. This means that for a site with a lot of graphics and other files, if you've got a lot of cookie data, you could be adding quite a lot of extra bandwidth to your site.
Cookies are also insecure and can be modified by the browser user, so shouldn't be used for anything the needs to be kept secure.
PHP sessions use a cookie behind the scenes to track the sessionID, but all other session data is kept on the server.
Therefore, given the choice between cookies and PHP sessions, I would put most things into the PHP session, especially in a shopping basket scenario.
Keeping a set of shopping basket data in the session is relatively simple:
Code:
//Add a new item:
$_SESSION['basket'][]=array('product'=>$_POST['product'],'qty'=>$_POST['qty']);
(very much simplified; there's obviously more to it than that, but demonstrates the principle)
Quote:
As the user builds up a cart full of stuff, is the data for that maintained on the server-side in a MySQL database or something?
|
As you suggest, the best solution is to store the order data in a database as the user adds items to his basket. This is better than storing basket data in the PHP session because it gives your system a better audit trail of what's happening, and also it allows you to write a system such that a user can add items to his basket and come back later, log in, and they'll still be there.
This is obviously a lot more work than just adding it to the session array; you'll need to design your database tables and write the code to read and write to them. But you're going to need to do that anyway at some point, so may as well start here.
Cheers.