One of the most common requirements any web designer/developer will come across is likely to be that of the small business taking its first steps online; a client with an established widget-selling company now wants to move into the national market and sell their widgets to the world.
What they need to do this (apart from a great-looking, functional, usable and accessible website!) is some sort of shopping-cart system to allow their customers to add, remove and update the products they wish to buy.
This article will walk through the simple steps to achieve this, using the server-side language PHP and a MySQL database.
Setting up the database
Let’s take as our example a bookseller. They are not the best-stocked bookseller in the world, having as they do only three titles in stock, but it is enough for our example. Let’s create the database and add some stock:
CREATE TABLE books (
id int(6) unsigned NOT NULL auto_increment,
title varchar(100) NOT NULL default '',
author varchar(100) NOT NULL default '',
price decimal(3,2) NOT NULL default '0.00',
PRIMARY KEY (id)
) TYPE=MyISAM;
INSERT INTO books VALUES (1, 'Where God Went Wrong', 'Oolon Colluphid', '24.99');
INSERT INTO books VALUES (2, 'Some More of God\'s Greatest Mistakes', 'Oolon Colluphid', '17.99');
INSERT INTO books VALUES (3, 'Who Is This God Person Anyway?', 'Oolon Colluphid', '14.99');
Now that step is out of the way, let’s create our shopping cart.
Identify our requirements
The cart we are going to build should be pretty familiar to most internet users. It will provide a means of displaying a message on every page of the site (along the lines of “You have 5 items in your shopping cart”), which when clicked will take the customer to a list of the items in the cart; each item may be removed or have its quantity updated.
As all of our stock details are stored in the database, the only piece of information that we need to store about each customer is the id of each product they have added to their cart. To do this, we are going to use PHP’s built-in session handling capabilities.
Using sessions in PHP
PHP’s session handling is very easy to understand.
To ‘switch it on’, simply add session_start(); at the top of your code; you can then store values (or arrays) in session variables:
$_SESSION['name'] = ‘Matthew’; $_SESSION['age'] = 31;
These $_SESSION variables will now be available to any PHP scripts on other pages (as long as you’ve included the session_start(); call first).
Continue reading “A simple PHP shopping cart script”