Приглашаем посетить
Ахматова (ahmatova.niv.ru)

Hack 66. Create a Shopping Cart

Previous
Table of Contents
Next

Hack 66. Create a Shopping Cart

Hack 66. Create a Shopping Cart 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.

6.17.1. The Code

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

Figure 6-38. The shopping cart page flow
Hack 66. Create a Shopping Cart


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() );
if (PEAR::isError($db)) { die($db->getMessage()); }

function get_db() { global $db; return $db; }

function get_products( )
{ 
	global $db; 
	$res = $db->query( "SELECT * FROM product", array( ) );  
	$out = array(); 
	if ( $res != null )
		while( $res->fetchInto( $row, DB_FETCHMODE_ASSOC ) ) { $out []= $row; } 
	return $out; 
}

function product_info( $id )
{ 
	global $db;

	$res = $db->query( "SELECT * FROM product WHERE id=?",
		array( $id ) );

	if ( $res != null )
	{
		$res->fetchInto( $row, DB_FETCHMODE_ASSOC );
		return $row;
	}
	return null; 
} 
?>

Save the code in Example 6-47 as index.php.

Example 6-47. The product page
<?php
require_once( "dblib.php" );
session_start();
$products = get_products();
?>
<html>
<head>
<title>My Products</title>
</head>
<style type="text/css">
h1 { border-bottom: 1px solid black; font-size: medium; margin-bottom: 10px; }
</style>
<script>
function buy( prod_id )
{
		document.getElementById( 'prod_id' ).value = prod_id;
		document.getElementById( 'buyform' ).submit();
		return null;
}
</script>
<body>
<form id="buyform" action="add.php" method="post">
<input type="hidden" name="prod_id" id="prod_id" value="" />
</form>
<table width="600" border="0" cellspacing="0" cellpadding="5">
<tr>
<td width="70%" valign="top">
<h1>Products</h1>
<table width="100%">
<?php foreach( $products as $product ) { ?>
<tr>
<td width="70%"><?php echo( $product['name'] ); ?></td>
<td width="15%" align="right">$<?php echo( $product['price'] ); ?></td>
<td width="15%" align="center"><a href="javascript:buy( <?php echo(
	$product['id'] ); ?> );">buy</a>
</tr>
<?php } ?>
</table>
</td>
<td width="30%" valign="top">
<h1>Shopping cart</h1>
<?php
if( isset( $_SESSION['cart'] ) ) {
?>
<!-- CART : <?php echo( join( ",", array_keys( $_SESSION['cart'] ) ) ); ?> -->
<table width="100%" cellspacing="0" cellpadding="5">
<?php
foreach( array_keys( $_SESSION['cart'] ) as $product ) {
$info = product_info( $product );
?>
<tr><td>
<?php echo( $info['name' ] ); ?>
</td></tr>
<?php } ?>
<tr><td align="center">
<a href="checkout.php">Checkout</a>
</td></tr>
</table>
<?php
}
?>
</td>
</tr>
</table>
</body>
</html>

Save the code in Example 6-48 as add.php.

Example 6-48. The script to add items to the cart
<?php
session_start();
if ( !isset( $_SESSION['cart'] ) )
       $_SESSION['cart'] = array(); 
$_SESSION['cart'][$_POST['prod_id']] = 1; 
header( "location: index.php" ); 
?>

Save the code in Example 6-49 as checkout.php.

Example 6-49. The checkout page
<?php
require_once( "dblib.php" );
session_start( );
?>
<html>
<head>
<title>Your Cart</title>
<script language="Javascript">
function submit_delete( )
{
		document.getElementById( "delform" ).submit( );
		return null;
}
</script>
<style type="text/css">
h1 { border-bottom: 1px solid black; font-size: medium; margin-bottom: 10px; }
</style>
</head>
<body>
<?php
if ( isset( $_SESSION['cart'] ) && count( $_SESSION['cart'] ) > 0 ) {
?>
<!-- CART : <?php echo( join( ",", array_keys( $_SESSION['cart'] ) ) ); ?> -->
<form id="delform" action="delete.php" method="post">
<table width="600">
<tr>
<th width="3%"></th>
<th width="77%">Product</th>
<th width="20%">Price</th>
</tr>
<?php
foreach( array_keys( $_SESSION['cart'] ) as $product )
{
		$prod = product_info( $product );
?>
<tr>
<td><input type="checkbox" name="ids[]" value="<?php echo( $product ); ?>" />
</td>
<td><?php echo( $prod['name'] ); ?></td>
<td align="right"><?php echo( $prod['price'] ); ?></td>
	</tr>
<?php } ?>
<tr>
<td></td>
<td align="center"><a href="javascript:submit_delete( )">Delete checked items</a>
&nbsp; &nbsp; &nbsp; &nbsp;
<a href="index.php">Return to store</a>
&nbsp; &nbsp; &nbsp; &nbsp;
<a href="buy.php">Buy these items</a>
</tr>
</table>
</form>
<?php } else { ?>
You should go and <a href="index.php">buy some stuff</a>.
<?php } ?>
</body>
</html>

Save the code in Example 6-50 as delete.php.

Example 6-50. The script to remove items from the cart
<?php
session_start( );
foreach( $_POST['ids'] as $did )
unset( $_SESSION['cart'][$did] );
header( "location: checkout.php" );
?>

The shopping cart starts with the index.php page, which shows the products from the database. Clicking on one of the products will add it to the shopping cart via calls going out to the add.php page, which sets up the session and adds the product to it. The add.php script then redirects the user back to the product page, which shows both the products and the contents of the shopping cart.

Once the shopping cart has some stuff in it, the user is given a link to the checkout.php page. That page shows the contents of the cart and has links to delete items from the cart. Those links go to the delete.php script, which deletes items from the cart and sends the user back to the checkout.php page.

6.17.2. Running the Hack

This hack starts with creating the database and loading it with the schema:

	% mysqladmin --user=root --password=password create shopcart
	% mysql --user=root --password=password shopcart < shopcart.sql

Now upload the PHP scripts to the server and surf over to the index.php page. You will see the store's home page, as shown in Figure 6-39.

On the lefthand side of the page is the list of products with links that the user can click to buy the products. Clicking on the link will post the product ID to the add.php script, which adds the product to the cart that is stored in the user's session variable.

The add.php script forwards the user back to the index.php page, which shows the updated cart on the righthand side of the display (as seen in Figure 6-40).

Figure 6-39. The index.php home page for the store
Hack 66. Create a Shopping Cart


Figure 6-40. After clicking on the "buy" link for Podcasting Hacks
Hack 66. Create a Shopping Cart


The next thing to do after clicking "buy" on all of the books is to check out. Clicking on the Checkout link will send the user to the checkout.php page, as shown in Figure 6-41.

Here the checkout page shows that three books have been put in the cart. The user now has the opportunity to select some items and remove them from the cart, or to continue to buy the items in the cart.

Deleting the books from the cart starts with selecting them, as shown in Figure 6-42.

After selecting the books, the user needs to click on the "Delete checked items" link to remove the items from the cart. The link submits the page to the delete.php script, which just removes the values from the cart array. The script then forwards the user back to the checkout page, as shown in Figure 6-43.

To finish off the cart you need to implement the "Buy these items" link. "Add a Buy Now Button" [Hack #62] covers the buy phase of the e-commerce cycle in depth.

Figure 6-41. The checkout page
Hack 66. Create a Shopping Cart


Figure 6-42. Selecting a couple of books to remove from the cart
Hack 66. Create a Shopping Cart


Figure 6-43. After removing the books from the cart
Hack 66. Create a Shopping Cart


6.17.3. See Also


Previous
Table of Contents
Next