O'Reilly logo

PHP Hacks by Jack D. Herrington

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #66. Create a Shopping Cart

Use cookies and sessions to create a simple shopping cart application.

This hack demonstrates a simple shopping cart application using PHP and session variables.

Figure 6-38 shows the relationship among the pages in the shopping cart application. The user starts on the index.php page and can traverse freely between there and the checkout.php page (which shows his shopping cart). On the index.php page, he can add items to the cart by clicking on the Add button, which submits the information to the add.php page and sends him back to the index.php page. From The checkout.php page, he can remove items, a process that follows the same routine as the add logic but uses the delete.php page and returns him to the checkout.php page.

The Code

Save the code in Example 6-45 as shopcart.sql.

The shopping cart page flow

Figure 6-38. The shopping cart page flow

Example 6-45. The shopping cart schema

DROP TABLE IF EXISTS product;
CREATE TABLE product ( 
	id MEDIUMINT NOT NULL AUTO_INCREMENT, 
	name TEXT, 
	price FLOAT, 
	PRIMARY KEY( id )
);

INSERT INTO product VALUES ( 0, "Code Generation in Action", 49.99 );
INSERT INTO product VALUES ( 0, "Podcasting Hacks", 29.99 );
INSERT INTO product VALUES ( 0, "PHP Hacks", 29.99 );

Save the code in Example 6-46 as dblib.php.

Example 6-46. The database library

<?php require_once( "DB.php" ); $dsn = 'mysql://root:password@localhost/shopcart'; $db =& DB::Connect( $dsn, array() ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required